Laravel通过枢轴急切加载?

时间:2017-03-15 11:02:52

标签: php laravel laravel-5 eloquent pivot

我试图通过数据透视表中的ID来加载一些数据。

现在我只是手动完成它,但想知道是否有办法通过雄辩的关系直接做到这一点?

$ids = $tournament->matches
                  ->pluck('users')
                  ->flatten()
                  ->pluck('pivot')
                  ->pluck('team_id')
                  ->unique();

$teams = \App\Models\Team::whereIn('id', $ids)->get()->keyBy('id');

$tournament->matches->each(function ($match) use ($teams) {
    $match->users->each(function ($user) use ($teams) {
        $user->team = @$teams[$user->pivot->team_id] ?: null;
    });
});

1 个答案:

答案 0 :(得分:1)

您可以返回最终扩展模型的Pivot实例。所以对于前在锦标赛中属于许多球队关系然后在锦标赛模型

/**
     * @param Model $parent
     * @param array $attributes
     * @param string $table
     * @param bool $exists
     * @return ProjectTeamPivot
     */
    public function newPivot(Model $parent, array $attributes, $table, $exists)
    {
        return new TeamPivot($parent, $attributes, $table, $exists);
    }

并在您的团队数据透视表中进行如下操作

use Illuminate\Database\Eloquent\Relations\Pivot;

class TeamPivot extends Pivot
{

    /**
     * @var array
     */
    protected $fillable = [];

    protected $casts = [];

   // this is the instance of model itself which represents the intermediate table so you can define any kind of relation as you would define in normal model load it eagerly like
   protected $with = []; // you can always load a model if you fill the relation name in this array
 }

了解更多信息,请访问此处 https://softonsofa.com/laravel-custom-pivot-model-in-eloquent/