[英]Laravel 5: DB::table() and relationship in Eloquent
I have a hasMany relationship between Community and LangCommunity and I am trying to sort by name field without losing the relationship in the view. 我在社区和LangCommunity之间具有hasMany关系,并且我试图按名称字段进行排序,而不会丢失视图中的关系。
Model Community 模范社区
protected $fillable = ['province_id', 'active', 'address', 'phone', 'google_map'];
public function langs()
{
return $this->hasMany('App\Models\LangCommunity');
}
Model LangCommunity 模特郎社区
protected $fillable = ['community_id', 'lang_id', 'name', 'text'];
public function community()
{
return $this->belongsTo('App\Models\Community');
}
In controller , I have: 在控制器中 ,我有:
$data['communities'] = DB::table('communities')
->join('lang_communities', 'communities.id', '=', 'lang_communities.community_id')
->select('communities.*', 'lang_communities.name')
->where('lang_communities.lang_id', '1')
->orderBy('lang_communities.name', 'asc')
->paginate($num);
This work, but I can't use the relationship in the view. 这项工作,但我不能在视图中使用关系。 I have tried to do it in the following way:
我尝试通过以下方式进行操作:
$data['communities'] = Community::with(['langs' => function($query)
{
$query
->where('lang_id', '1')
->join('communities', 'communities.id', '=', 'lang_communities.community_id')
->orderBy('lang_communities.name', 'asc');
}])->paginate($num);
But this does not sort by name. 但这不是按名称排序。 Any idea?
任何想法?
Ok. 好。 I have managed to solve it ;)
我设法解决了;)
$data['communities'] = Community::join('lang_communities', 'communities.id', '=', 'lang_communities.community_id')
->select('communities.*', 'lang_communities.name')
->where('lang_communities.lang_id', '1')
->orderBy('lang_communities.name', 'asc')
->paginate($num);
Did you try : 你试过了吗 :
$data['communities'] = Community::with(['langs' => function ($q) {
$q->orderBy('name', 'asc');
}])
->whereHas('langs', function ($query) {
$query->where('lang_id', 1);
})->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.