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