Laravel在雄辩的范围和查询中使用select [英] Laravel using select in Eloquent scope and query

查看:72
本文介绍了Laravel在雄辩的范围和查询中使用select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试清理我编写的一些代码.

I'm trying to clean up some code that I made.

这是当前代码:

$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的范围,如下所示:

So I made a scope called withFunction that looks like this:

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.我希望它看起来像这样:

But because I use this scope where I select specific column, I cant use the select in my query as well. I want it to look like this:

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

因此,我指定了从范围和查询本身返回的列.我知道查询中不能有2个select,但是有什么可能的方法吗?

So I specify the columns returned from the scope and from the query itself. I know I can't have 2 select's in a query, but is there any way this would be possible?

如果您只需返回范围中的列以在整个应用程序中使用它,那就太好了.

Would be great if you could just return columns in the scope to use it through the whole application.

推荐答案

查看

Look at addSelect(). When you use select(), your are overriding all the other selected columns and only selecting the one. By using addSelect() you will append the column to the selected columns rather than replace it.

因此,作为一般规则,应在调用任何添加列的作用域之前调用select(),这些作用域应使用addSelect().

So as a general rule you should call select() before calling any scopes that add columns, and those scopes should use addSelect().

也...实际上,您不需要返回范围中的$ query,因为您正在与查询生成器对象进行交互.有点像老派参考文献(&).

Also... you actually do not need to return the $query in your scope because you are interacting with the query builder object. It kinda works like old school references (&).

这篇关于Laravel在雄辩的范围和查询中使用select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆