从 Eloquent 获取 Laravel 中没有附加和关系的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47182217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:55:38  来源:igfitidea点击:

Get data without appends and relations in Laravel from Eloquent

phplaraveleloquent

提问by shyammakwana.me

I have model Projectwhich has some $appendsand some relations like pages, brands, statusetc.

我有模型Project具有一定$appends有些关系像pagesbrandsstatus等等。

And in $appendsit has pages, and in Pagemodel it has lot of other $appends. Now while I do Project::find($id)it retrieves project, it's pages and other models which belongs to Page. And I havn't done with, so for each page it fires lots of queries.

$appends它里面有pages,在Page模型中还有很多其他的$appends。现在,当我Project::find($id)检索项目时,它是属于 Page 的页面和其他模型。而且我还没有完成with,因此对于每个页面,它都会引发大量查询。

Without using

不使用

DB::table('projects')->where('id', $id)->get();

Is there any better approach to load only Project model, no relation, no appends, nothing via Eloquent ?

有没有更好的方法来只加载 Project 模型,没有关系,没有附加,没有通过 Eloquent 加载?

采纳答案by Alex Harris

Unfortunately thats not how it works. If you want to removethe appends you could do so as follows:

不幸的是,这不是它的工作原理。如果要删除附加内容,可以按如下方式操作:

$project = Project::find(1);
$project->setAppends([]);

return $project; //no values will be appended

However if those appends are doing database calls and you prefer not to you should rexamine whether or not it makes sense for the appends to be there. It's really a matter of whether you think it makes sense for the appendsto alwaysbe included or not.

但是,如果这些附加正在执行数据库调用并且您不想这样做,则应该重新检查附加在那里是否有意义。这是真正的你是否觉得很有道理的事情appends总是被包含与否。

回答by Игорь Балашов

It was usefull for me:

这对我很有用:

$services = Service::all()->makeHidden(['appendField1', 'appendField2'])->toArray();

回答by Alican Ali

I had a problem with the appendfields of the second model i was trying to access, it was going into an infinite loop. So in User Model;

我试图访问的第二个模型的附加字段有问题,它进入了一个无限循环。所以在用户模型中;

Instead of

代替

return $this->organisation->is_enabled;

using:

使用:

return $this->organisation->setAppends([])->is_enabled;

Solved the problem for me since setAppends([]) function is unappending the unnecessary relations

为我解决了问题,因为 setAppends([]) 函数取消了不必要的关系

回答by LetsCMS Pvt Ltd

You can use the custom query to get the results as like:

您可以使用自定义查询来获得如下结果:

DB::table('users as u')->join('state_history as sh', 'sh.user_id', '=', 'u.id')->where('u.id','=', $id)->join('users as u1','sh.team_id','=','u1.id')->select('u.name','sh.state','sh.created_at','u1.name as tname')->orderBy('sh.created_at', 'desc')->get();