我正在 laravel 5.4
中构建一个小型应用程序,其中我有两个模型 Contact
和 Companies
我有很多它们之间有很多关系,在我的 Contact Model:
public function company()
{
return $this
->belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')->withTimestamps();
}
现在在某个地方我想要当前公司,即我想要 latest()
first()
。或者orderBy
, created_by
desc
得到first()
行。为此,我必须做这样的事情:
$contacts = Contact::where('name', 'LIKE', '%'. $request->search_input. '%')
->orWhere('email', 'LIKE', '%'. $request->search_input. '%')
->orWhereHas('company', function ($q) use($request) {
$q->where('name', 'LIKE', '%'. $request->search_input. '%');
})
->with('company')
->orderBy('created_at', 'desc')
->paginate(50);
foreach ($contacts as $contact)
{
$contact->company = $contact->company()->withPivot('created_at')->orderBy('pivot_created_at', 'desc')->first();
}
为了删除 foreach
,我尝试在我的 Contact
模型中使用一个新关系:
public function currentCompany()
{
return $this
->belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')
->withTimestamps()
->orderBy('created_at', 'desc')
->first();
}
但是在 Controller 中获取时:
$contacts = Contact::where('name', 'LIKE', '%'. $request->search_input. '%')
->orWhere('email', 'LIKE', '%'. $request->search_input. '%')
->orWhereHas('currentCompany', function ($q) use($request) {
$q->where('name', 'LIKE', '%'. $request->search_input. '%');
})
->with('CurrentCompany')
->orderBy('created_at', 'desc')
->paginate(50);
但它给我带来了错误,是否有任何 Eloquent
方式或Collection
方式来删除这个foreach
。
最佳答案
在闭包中使用first()
-
$contacts = Contact::where('name', 'LIKE', '%'. $request->search_input. '%')
->orWhere('email', 'LIKE', '%'. $request->search_input. '%')
->with(['company'=>function ($q) use($request) {
$q->where('name', 'LIKE', '%'. $request->search_input. '%')->first();
}])
->orderBy('created_at', 'desc')
->paginate(50);
或者像这样-
$contacts = Contact::where('name', 'LIKE', '%'. $request->search_input. '%')
->orWhere('email', 'LIKE', '%'. $request->search_input. '%')
->orWhereHas('company', function ($q) use($request) {
$q->where('name', 'LIKE', '%'. $request->search_input. '%');
})
->with(['company'=>function($q){
$q->first();
}])
->orderBy('created_at', 'desc')
->paginate(50);
这样你就不需要做任何额外的foreach
循环。
关于php - 在 laravel 的急切加载中从多对多关系中获取第一个或最新的第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48376610/