eloquent:如何在模型本身内加载和设置模型变量?

时间:2016-11-10 18:34:41

标签: php laravel model eloquent

Laravel文档建议采用以下方式建立一个雄辩的模型:

$user = user::with($conditions)->first();

如果我想在模型中设置我的雄辩模型怎么办:

$user = new user();
$user->setup($conditions);
// class definition
class user extends Eloquent{
    public function setup($conditions){
        // load current object with table data
        // something like
        $this->where($conditions)->first();
        // previous line output is dangling, is ok to assign it to $this variable?
    }
}

1 个答案:

答案 0 :(得分:1)

如果您从Eloquent模型扩展,您可以尝试以下方法。我假设您有一个唯一的id列。

public function setup($conditions)
{
    $model = self::with($conditions)->first();

    if (! is_null($model)) {
        $this->exists = true;
        $this->forceFill(self::find($model->id)->toArray());
    }

    return $this;
}

希望这可以解决您的问题。