拉拉威尔包含关系的关系



我有关系

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

现在,我想检查Trainee是否包含来自CompanyPoke。我怎样才能做到最干净?我更喜欢$trainee->containsPokeFrom($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();
}
}

您可以使用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
}

最新更新