Php 如果是第一个或新的,如何使用firstOrNew

Php 如果是第一个或新的,如何使用firstOrNew,php,laravel,laravel-5.2,Php,Laravel,Laravel 5.2,我想使用firstOrNew,比如: table::firstOrNew(['ip'=>'15.25.36.12', 'linke'=>'http://example.com']) ->where('created_at','>=',date('Y-m-d H:i:s', time()-86400); 我用了这样的东西: $data = table::where('ip', '15.25.36.12')->where('link','http://exam

我想使用firstOrNew,比如:

table::firstOrNew(['ip'=>'15.25.36.12', 'linke'=>'http://example.com'])
->where('created_at','>=',date('Y-m-d H:i:s', time()-86400);
我用了这样的东西:

    $data = table::where('ip', '15.25.36.12')->where('link','http://example.com')->
where('created_at','>=', date('Y-m-d H:i:s', time()-86400));
    if(!$data->exists())
    {
      $data = new table;
      $data->field = 'foo';
      $data->save(); 
    }
但效果不太好!因为它从文档中添加了两行相同的内容:

firstOrCreate方法将尝试使用给定的列/值对定位数据库记录。如果在数据库中找不到模型,将插入具有给定属性的记录

firstOrNew方法(如firstOrCreate)将尝试在数据库中查找与给定属性匹配的记录。但是,如果找不到模型,将返回新的模型实例。请注意,firstOrNew返回的模型尚未持久化到数据库中。您需要手动调用save来持久化它

因此,要么
save()
您的新记录,要么使用
first或create

尝试此代码

$data = table::updateOrCreate([
                              'ip'=>'15.25.36.12', 
                              'linke'=>'http://example.com'
                               ],[
                               'field' => 'foo'
                             ])
                    ->whereDate('created_at', '>=',Carbon::now()->subDay());

为了澄清起见,firstOrNew在数据库中搜索包含给定信息的记录。如果找到,则返回包含记录信息的模型实例,否则只创建一个新的模型实例,它不保存内容为此,您必须手动触发保存

范例

// Assuming that this record does not exist in database
$a = Table::firstOrNew([
    'name' => 'John Doe',
    'age'  => 16
]); 

$a->nickname = "jDoe";
$a->save(); // Save the record to the database using insert
// Assuming that this record does not exist in database
$a = Table::firstOrCreate([
    'name' => 'John Doe',
    'age'  => 16
]); 

$a->nickname = "jDoe";

// Fires a update query as opposed to insert query in above example
$a->save();
这使您有机会在保存之前向对象添加其他相关信息

要立即创建记录,请使用first或create功能。它还将返回一个模型实例,但同时也会创建记录。现在,如果您保存它,它将触发一个更新查询

范例

// Assuming that this record does not exist in database
$a = Table::firstOrNew([
    'name' => 'John Doe',
    'age'  => 16
]); 

$a->nickname = "jDoe";
$a->save(); // Save the record to the database using insert
// Assuming that this record does not exist in database
$a = Table::firstOrCreate([
    'name' => 'John Doe',
    'age'  => 16
]); 

$a->nickname = "jDoe";

// Fires a update query as opposed to insert query in above example
$a->save();

您是否尝试在
where
builder上像这样使用
data::where()->firstOrNew([])
方法?我只是感兴趣是的,我不想使用
first或create()
因为它不是我的目标。我想在数据中创建新的
,如果它已经存在,则将其重定向到其他页面方法
firstOrNew
的操作实际上与您的操作相同。在引擎盖下:
updateOrCreate
用于较旧版本的
Laravel
,我使用的是5.2版