【问题标题】:Laravel use morpMany with where clauseLaravel 使用带有 where 子句的 morpMany
【发布时间】:2017-03-06 14:47:31
【问题描述】:

嗨,我正在 laravel 框架中实现多态关系 目前我有 2 个模型 信用记录和用户

Creditlog 具有 sourceable 属性,可用于 User 模型

class CreditLog extends Model
{
...


    public function sourceable()
    {
        return $this->morphTo();
    }

...
}

然后在用户中我有这样的关系

class User extends Authenticatable
{

    public function creditLogs()
    {
        return $this->morphMany('App\Models\CreditLog', 'sourceable');
    }

}

然后在某些控制器中我需要获取用户信用日志

$user = User::find($id);
$CreditLogs = $user->creditLogs;

我可以在 creditLogs 方法中添加参数吗,我的意思是 laravel morphMany 可以像这样添加参数

$CreditLogs = $user->creditLogs
                        ->where('created_at', '>=', $inputReq['start'])
                        ->where('created_at', '<=', $inputReq['end']);

感谢您对问题的回答

【问题讨论】:

    标签: php laravel eloquent polymorphism


    【解决方案1】:

    您可以将load() 方法与lazy eager loading 一起使用。

      $user->load(['creditLogs' => function ($query) use($inputReq) {
            $query->where('created_at', '>=', $inputReq['start'])
                    ->where('created_at', '<=', $$inputReq['end']);
        }]);
    

    或者使用with()方法和Constraing eager loading

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 2011-08-02
      • 1970-01-01
      相关资源
      最近更新 更多