在BaseModel上急切加载

时间:2014-06-03 03:46:54

标签: php laravel eloquent

目前在模型中我执行以下操作以自动加载所有关系:

public static $eagerLoad = ['country', 'product', 'membership.package'];

public function newQuery($excludeDeleted = true)
{
    $query = parent::newQuery(true);
    return $query->with(static::$eagerLoad);
}

我怎样才能将它传输到BaseModel?

当我尝试时,返回eloquent call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object

更新

在我的BaseModel中我喜欢这个:

public function newQuery($excludeDeleted = true)
{
    if(property_exists(get_class($this), 'eagerLoad'))
    {                       
        $query = parent::newQuery(true);
        return $query->with($this::$eagerLoad);
    }
}

返回Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsTo::__construct() must be an instance of Illuminate\Database\Eloquent\Builder, null given, called in C:\xampp\htdocs\firebolt\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 713 and defined

如果我留空或返回false,则会抛出call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object

1 个答案:

答案 0 :(得分:2)

您不需要使用它(现在以自动方式执行此操作以自动加载),因为您需要做的只是在模型中添加protected $with属性,例如:

protected $with = ['country', 'product', 'membership.package'];

现在,您的模型将自动加载$with中提供的相关模型。所以如果你做这样的事情:

$model = Model::find(1);

所有相关模型也将热切地加载此$model对象。