【问题标题】:How to eager load a custom made relationship?如何急切地加载定制的关系?
【发布时间】:2019-09-08 11:58:51
【问题描述】:

我有一个statuses 表,我在其中存储多个模型(表)的状态。例如:

comments
id | status | text    | ... 
---------------------------
1  | 2      | great.. |
2  | 3      | thats.. |

posts
id | status | body | ...
---------------------------
1  | 4      | hey..| 
2  | 5      | i w..|

statuses
id | type    | title     | ...
---------------------------
1  | comment | succes    |
2  | comment | error     | 
3  | comment | published |
4  | post    | deleted   |
5  | post    | pending   |

这里我可以通过 belongsTo 关系访问相应的记录。

class Post extends Model {
    public function status()
    {
        return $this->belongsTo(Status::class, ....);
    }
}

但我想要的是急切加载 cmets 的状态选项,以便我可以下拉或类似的东西。我可以创建与 where 的自定义关系,但不会急于加载。

有什么建议吗?

【问题讨论】:

  • 您可以在主模型中使用with,并可以加载关系数据。喜欢Post::with('status')。参考this

标签: laravel


【解决方案1】:

您可以为此使用Local Scopes

状态模型

class Status extends Model
{
    public static $COMMENT_STATUS = 'comment';
    public static $POST_STATUS = 'post';

    public function scopeForComments($query)
    {
        return $query->where('type', self::$COMMENT_STATUS);
    }

    public function scopeForPosts($query)
    {
        return $query->where('type', self::$POST_STATUS);
    }
}

然后,在您的控制器中:

MyController.php

Status::forComments()->get(); //List up all the statuses for comments
Status::forArticles()->get(); //List up all the statuses for articles

【讨论】:

  • 实际上我正在寻找调用模型的状态(评论状态)。所以根据我的表格,Post::with('status')->get(); 需要什么样的关系。当我调用关系时,它必须从状态表中获取类型为comment 的记录。
  • 我没有问题了解该模型的当前状态。但我需要调用所有可能的评论状态(在这种情况下已删除,待处理)
  • 我可以使用公共函数statuses() { return Status::where('type', self::class); } 方法来调用该模型的所有状态,但我不能急切加载
  • 我想我需要某种多态关系,我可以将表值与模型名称进行比较。就我而言,获取类型为 App\Comment 的所有记录
  • 在您的更新中,您如何获得评论模型的所有状态(成功、错误、已发布)。
猜你喜欢
  • 2021-04-28
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
相关资源
最近更新 更多