laravel updateOrCreate()与动态表

时间:2016-02-03 01:43:27

标签: laravel-5.1

我正在使用项目,其中表格一直在创建,具体取决于用户添加新属性,因此对于我的模型,我有以下

    class Hotel extends Model
{
    public function __construct($hotel)
    {
        $this->table = $hotel;
    }

    protected $fillable = ['date', 'sold', 'sold_diff', 'rev', 'rev_diff', 'row', 'date_col', 'sold_col', 'rev_col'];

}

我可以通过

在控制器中使用该表
$hotel_table = new Hotel($table);

但是当我在表中添加或更新行时,我喜欢使用Model :: updateOrCreate(),我不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

In Laravel 5.2 you can use simply like this

    class Hotel extends Model
    {
        protect $table = 'hotels'

        protected $fillable = ['date', 'sold', 'sold_diff', 'rev', 'rev_diff', 'row', 'date_col', 'sold_col', 'rev_col'];
// protected $guarded = []; you can use this instead of `$fillable` this is for all columns fillable

    }

now in your controller you can use

Model::update();
Model::create();

答案 1 :(得分:0)

这是updateOrCreate函数的签名 “static Model updateOrCreate(array $ attributes,array $ values = array())”

要更新或创建,您可以传递必须满足的条件,将表更新为第一个参数,将值更新为第二个参数。

例如。

  $primaryKey = isset($request->input('id')) ? $request->input('id') : null;

  $myModel = Model::updateOrCreate(['id' => $primaryKey], $request->all());

因此,如果 id 在请求对象中,则表格将被更新,但如果不是,则会创建新记录。

相关问题