在没有雄辩的情况下,如何永远无法获得模型?
我知道,我可以使用with()
或 donthave()在Laravel(9)中获取模型数据,但我从不想取模型没有关系的数据,因此在所有CRUD功能中始终用()函数编写,这很烦人。
有没有一种方法可以直接在模型类中直接使用关系的过滤器模型?
在= ['foo']; 上添加保护$将关系添加到每个记录中,但仍包括没有关系的关系。
作为对此的可选奖励:也许旁路很不错,因此总的来说,所有结果都会有关系,但对于一个特定的路径get /all_data < /code>,预选前的序列将被绕过。
I know, that I can fetch Model data based on their relationship existence using with()
or doesntHave()
in Laravel (9), but I never ever want to fetch Model data without a relationship, thus it is annoying to always write the with()
function in all CRUD functions.
Is there a way to pre-filter models without a relationship directly in the Model class?
Adding protected $with = ['foo'];
adds the relationships to every record, but is still including the ones without a relationship.
As an optional bonus to that: Maybe a bypass is nice to have, so that in general all results will have relationship but maybe for one specific path GET /all_data
the pre-selection would be bypassed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以默认启用
急切的加载
如果将关系添加到$的情况下,则使用
属性属性,如下所述: https://laravel.com/docs/docs/9.x/eloquent-relations-relations.x/eloquent-relations.unations.默认文档读取:
===== edit1
另一个选项是使用
全局范围
https:https:// laravel 。您可以从这里走,可以添加更多逻辑以排除没有关系的模型。
===== edit2
额外的逻辑将从文档中添加此信息:
https://laravel.com/laravel.com/docs/docs/9.x/雄辩的关系#查询利用关系存在
You can enable
eager loading by default
if you add the relationship to the$with
property of the model as described here: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading-by-defaultThe documentation reads:
=====Edit1
Another option is using
Global Scopes
https://laravel.com/docs/9.x/eloquent#global-scopes.You can go from here, you can add some more logic to exclude models without the relationship.
=====Edit2
The extra logic will be adding this from the documentation:
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence