Laravel包含关系的关系

时间:2018-11-19 11:42:42

标签: php laravel relation

我有关系

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

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

现在,我要检查Trainee是否包含来自Poke的{​​{1}}。我怎样才能做到最干净?我更喜欢Company之类的东西,因为我正在刀片文件中使用它,但是如果那不是一个选择,那没关系。

2 个答案:

答案 0 :(得分:3)

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

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();
    }
}

答案 1 :(得分:0)

您可以使用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
}
相关问题