Laravel 包含关系的关系

Laravel contains relation of relation

我有关系

Trainee->hasMany->Poke
Company->hasMany->Poke

Poke->belongsTo->Trainee
Poke->belongsTo->Company

现在,我想检查 Trainee 是否包含来自 CompanyPoke。我怎样才能做到最干净?我更喜欢 $trainee->containsPokeFrom($company); 之类的东西,因为我在我的 blade 文件中使用它,但如果那不是一个选项,那也没关系。

您可以使用with()方法获取数据。

示例:

public function getTrainee()
{
    return Trainee::with('Poke.Company')->get();
    // Here you will find all trainee which associated with multiple pokes which belongs to a company
}

您将在 pokes 关系方法上使用 exists() 方法:

class Trainee extends Model
{
    public function pokes()
    {
        return $this->hasMany(Poke::class);
    }

    public function containsPokeFrom(Company $company)
    {
        return $this->pokes()->where(function ($poke) use ($company) {
            $poke->where('company_id', $company->getKey());
        })->exists();
    }
}