【发布时间】:2018-05-03 23:23:16
【问题描述】:
我在 Community 和 LangCommunity 之间有一个 hasMany 关系,我正在尝试按名称字段排序而不丢失视图中的关系。
模特社区
protected $fillable = ['province_id', 'active', 'address', 'phone', 'google_map'];
public function langs()
{
return $this->hasMany('App\Models\LangCommunity');
}
LangCommunity 模型
protected $fillable = ['community_id', 'lang_id', 'name', 'text'];
public function community()
{
return $this->belongsTo('App\Models\Community');
}
在控制器中,我有:
$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);
这项工作,但我不能使用视图中的关系。我试图通过以下方式做到这一点:
$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);
但这不是按名称排序的。有什么想法吗?
【问题讨论】:
标签: php laravel sorting inner-join relationship