在没有雄辩的情况下,如何永远无法获得模型?

发布于 2025-01-27 11:58:51 字数 330 浏览 3 评论 0原文

我知道,我可以使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴意少年 2025-02-03 11:58:51

您可以默认启用急切的加载如果将关系添加到$的情况下,则使用属性属性,如下所述: 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/雄辩的关系#查询利用关系存在

protected static function boot(){
        parent::boot();
        static::addGlobalScope('relation', function($builder){
            $builder->has('relation')->with('relation');
        });
}

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-default

The documentation reads:

Sometimes you might want to always load some relationships when
retrieving a model. To accomplish this, you may define a $with
property on the model:

=====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

protected static function boot(){
        parent::boot();
        static::addGlobalScope('relation', function($builder){
            $builder->has('relation')->with('relation');
        });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文