How addSelect() Builder method works in Laravel

老子叫甜甜 提交于 2019-12-05 07:01:57
plaha

If you need default values from select and add some extra, you can use this construction:

$usersWithFlights = User::with(['flights'])->select()->addSelect(DB::raw('1 as number'))->get();

At first take a look at the addSelect method:

public function addSelect($column)
{
    $column = is_array($column) ? $column : func_get_args();
    $this->columns = array_merge((array) $this->columns, $column);
    return $this;
}

This just adds the column(s) by merging with existing selected columns. So, when you use something like this:

$usersWithFlights = User::with(['flights'])->addSelect(DB::raw('1 as number'))->get();

The query becomes select 1 as number from flights and since your relation depends on a column value in the parent query so without any real column value there are no related records retrived. To check the queries you may try something like this:

\DB::enableQueryLog();
$usersWithFlights = User::with(['flights'])->addSelect(DB::raw('1 as number'))->get();
dd(\DB::getQueryLog());

Also, if you use a real column name in add select and if you don't select the related column for example, if you use addSelect('someString') then you'll get no related records either because you've to also select the related column that makes the relation and in this case you may try something like this:

$usersWithFlights = User::with(['flights'])->addSelect(['id', 'someString']))->get();

Test:

This is a test result of DB::getQueryLog() where I've used something similar but with different tables in my DB which is:

Post->with('comments')->addSelect(DB::raw('1 as number'))->get();
dd(DB::getQueryLog());

Result:

0 => array:3 [▼
  "query" => "select 1 as number from "posts""
  "bindings" => []
  "time" => 9.0
  ]
1 => array:3 [▼
  "query" => "select * from "comments" where "comments"."post_id" in (?)"
  "bindings" => array:1 [▼
    0 => null
  ]
  "time" => 1.0
]

Update:

The addSelect method is usefull when you've a query object at hand with some selected fields and later you want to add more fields in the select list so aan example could be like this:

$userWithFlights = User::with('flights')->select(['id', 'someColumn']);
// Some code ... 
if(SomeCondition) {
    // So, now the query will be something like this:
    // ->select(['id', 'someColumn', 'anotherField'])
    $userWithFlights->addSelect('anotherField');
}

$result =  $userWithFlights->get();

If you want to specifi some fields to be selected then you may use select($fieldsArray) instead. You may also try something like this:

$userWithFlights = User::with('flights')->get(['id', 'someColumn']);

Also you may try something like this:

$userWithFlights = User::with(['flights' => function($query) {
    $query->select('user_id', 'flight_title');
}])->get(['id', 'someColumn']);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!