Laravel - 通过带有急切负载的数据透视表的一对一关系

Spa*_*gCS 5 eager-loading laravel

我有这样的关系

  • 一个运动可以有多个步骤
  • 一个步骤可以属于多个动作

因此,必须创建一个数据透视表和一个belongsToMany关系,但我的数据透视表有一些额外的列,例如finishedorder

我想要有两种关系,一种是从运动中获取所有步骤,另一种是从运动中获取当前步骤(最后完成的步骤)

我知道如何获得所有步骤

public function steps()
{
    return $this->belongsToMany(MovementStep::class, 'movement_movement_steps')
        ->withPivot('order', 'finished')
        ->orderBy('pivot_order');
}
Run Code Online (Sandbox Code Playgroud)

但目前的步骤又如何呢?我需要这种关系,但只返回一条记录并能够立即加载它,因为我将其传递给 vue.js

public function current_step()
{
    return $this->belongsToMany(MovementStep::class, 'movement_movement_steps')
        ->withPivot('order', 'finished')
        ->where('finished', true)
        ->orderBy('pivot_order', 'desc');
}
Run Code Online (Sandbox Code Playgroud)

请注意,我想在没有额外包的情况下做到这一点

替代解决方案,但带有额外的包: Laravel hasOne 通过数据透视表(不是标记为正确的答案,来自 @cbaconnier 的答案)

cba*_*ier 4

与 @mrhn 提供的答案不同的方法是创建自定义关系。来自 Spatie 的布伦特(Brent)就此发表了一篇精彩的文章

虽然我的答案将执行与staudenmeir 包提供的查询完全相同的查询,但它让我意识到,无论您使用该包、此答案还是 @mrhn 答案,您都可以避免 n+1 查询,但您最终可能仍然会大量的水合模型。

在这种情况下,我认为不可能避免使用其中一种方法。不过,缓存可能是一个答案。

由于我不完全确定您的架构,因此我将使用我之前的答案中的用户照片示例提供我的解决方案。

用户.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    public function photos()
    {
        return $this->belongsToMany(Photo::class);
    }

    public function latestPhoto()
    {
        return new \App\Relations\LatestPhotoRelation($this);
    }
}
Run Code Online (Sandbox Code Playgroud)

最新照片关系.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    public function photos()
    {
        return $this->belongsToMany(Photo::class);
    }

    public function latestPhoto()
    {
        return new \App\Relations\LatestPhotoRelation($this);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

<?php


namespace App\Relations;

use App\Models\User;
use App\Models\Photo;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\Relation;

class LatestPhotoRelation extends Relation
{

    /** @var Photo|Builder */
    protected $query;

    /** @var User */
    protected $user;

    public function __construct(User $user)
    {
        parent::__construct(Photo::query(), $user);
    }

    /**
     * @inheritDoc
     */
    public function addConstraints()
    {
        $this->query
            ->join(
                'user_photo',
                'user_photo.photo_id',
                '=',
                'photos.id'
            )->latest();

            // if you have an ambiguous column name error you can use
            // `->latest('movement_movement_steps.created_at');`
    }

    /**
     * @inheritDoc
     */
    public function addEagerConstraints(array $users)
    {
        $this->query
            ->whereIn(
                'user_photo.user_id',
                collect($users)->pluck('id')
            );
    }

    /**
     * @inheritDoc
     */
    public function initRelation(array $users, $relation)
    {
        foreach ($users as $user) {
            $user->setRelation(
                $relation,
                null
            );
        }
        return $users;
    }

    /**
     * @inheritDoc
     */
    public function match(array $users, Collection $photos, $relation)
    {
        if ($photos->isEmpty()) {
            return $users;
        }

        foreach ($users as $user) {
            $user->setRelation(
                $relation,
                $photos->filter(function (Photo $photo) use ($user) {
                    return $photo->user_id === $user->id;  // `user_id` came with the `join` on `user_photo`
                })->first() // Photos are already DESC ordered from the query
            );
        }

        return $users;
    }

    /**
     * @inheritDoc
     */
    public function getResults()
    {
        return $this->query->get();
    }
}

Run Code Online (Sandbox Code Playgroud)

与 Brent 文章的主要区别在于,Collection我们返回的是最新的 Photo ,而不是使用 a Model