简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM