Laravel Eloquent: How to get only certain columns from joined tables

前端 未结 15 2432
礼貌的吻别
礼貌的吻别 2020-12-02 07:57

I have got 2 joined tables in Eloquent namely themes and users.

theme model:

public function user() {
  return $this->belongs_to(         


        
15条回答
  •  有刺的猬
    2020-12-02 08:25

    user2317976 has introduced a great static way of selecting related tables' columns.

    Here is a dynamic trick I've found so you can get whatever you want when using the model:

    return Response::eloquent(Theme::with(array('user' => function ($q) {
        $q->addSelect(array('id','username'))
    }))->get();
    

    I just found this trick also works well with load() too. This is very convenient.

    $queriedTheme->load(array('user'=>function($q){$q->addSelect(..)});
    

    Make sure you also include target table's key otherwise it won't be able to find it.

提交回复
热议问题