簡體   English   中英

Laravel在Eloquent范圍和查詢中使用select

[英]Laravel using select in Eloquent scope and query

我正在嘗試清理我制作的一些代碼。

這是當前的代碼:

$message = Message::with('comments')
   ->join('users', 'messages.created_by', '=', 'users.id')
   ->join('team_user', 'messages.created_by', '=', 'team_user.user_id')
   ->join('teams', 'team_user.team_id', '=', 'teams.id')
   ->join('roles', 'team_user.role_id', '=', 'roles.id')
   ->select('messages.id',  'messages.message', DB::raw('CONCAT(users.first_name, " ", users.last_name) AS created_by_name'), DB::raw('CONCAT(roles.name, " ", teams.name) AS function'))
   ->findOrFail($id); 

我試着這樣做:

$message = Message::with('comments')
   ->join('users', 'messages.created_by', '=', 'users.id')
   ->withFunction()
   ->findOrFail($id);

所以我創建了一個名為withFunction的范圍,如下所示:

return $query->join('team_user', 'messages.created_by', '=', 'team_user.user_id')
   ->join('teams', 'team_user.team_id', '=', 'teams.id')
   ->join('roles', 'team_user.role_id', '=', 'roles.id')->select(DB::raw('CONCAT(roles.name, " ", teams.name) AS function'));

但是因為我在選擇特定列時使用了這個范圍,所以我也不能在查詢中使用select。 我希望它看起來像這樣:

$message = Message::with('comments')
   ->join('users', 'messages.created_by', '=', 'users.id')
   ->withFunction()
   ->select('messages.id', 'messages.message')
   ->findOrFail($id);

所以我指定從作用域和查詢本身返回的列。 我知道我在查詢中不能有2個選擇,但是有什么方法可以實現嗎?

如果您可以只返回范圍中的列以在整個應用程序中使用它,那將會很棒。

看看addSelect() 當您使用select()時,您將覆蓋所有其他所選列,並僅選擇一列。 通過使用addSelect(),您可以將列附加到選定的列而不是替換它。

因此,作為一般規則,您應在調用任何添加列的作用域之前調用select(),並且這些作用域應使用addSelect()。

另外......您實際上不需要在范圍內返回$ query,因為您正在與查詢構建器對象進行交互。 它有點像舊學校參考(&)。

問題似乎歸結為get()如何工作。

    $original = $this->columns;

    if (is_null($original)) {
        $this->columns = $columns;
    }

如果沒有定義其他選擇,則僅添加“*”以進行選擇。

您需要在構建器上顯式調用select('*')

$message = Message::with('comments')
   ->select('*')
   ->join('users', 'messages.created_by', '=', 'users.id')
   ->withFunction()
   ->select('messages.id', 'messages.message')
   ->findOrFail($id);

或者在你的范圍中添加它,這是5.3項目的一個例子。

public function apply(Builder $builder, Model $model)
{
    if(is_null($builder->getQuery()->columns)){
        $builder->addSelect('*');
    }
    $builder->addSelect(DB::raw('...'));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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