本文介绍了Laravel 5:Eloquent 中的 DB::table() 和关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Community 和 LangCommunity 之间有 hasMany 关系,我正在尝试按名称字段排序,而不会丢失视图中的关系.

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.

示范社区

protected $fillable = ['province_id', 'active', 'address', 'phone', 'google_map'];

public function langs()
{
    return $this->hasMany('App\Models\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);

这项工作,但我不能在视图中使用关系.我尝试通过以下方式做到这一点:

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);

这篇关于Laravel 5:Eloquent 中的 DB::table() 和关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:44