繁体   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