簡體   English   中英

Laravel 5:Eloquent中的DB :: table()和關系

[英]Laravel 5: DB::table() and relationship in Eloquent

我在社區和LangCommunity之間具有hasMany關系,並且我試圖按名稱字段進行排序,而不會丟失視圖中的關系。

模范社區

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

這項工作,但我不能在視圖中使用關系。 我嘗試通過以下方式進行操作:

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

但這不是按名稱排序。 任何想法?

好。 我設法解決了;)

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

你試過了嗎 :

$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM