使用Eloquent查找或创建

时间:2013-12-01 05:26:50

标签: php laravel laravel-4 eloquent

我最近开始使用LaravelEloquent,并且想知道缺少模型的查找或创建选项。你总是可以写,例如:

$user = User::find($id);
if (!$user) {
    $user = new User;
}

但是,有没有更好的方法来查找或创建?在示例中似乎微不足道,但对于更复杂的情况,获取现有记录并更新或创建新记录将非常有用。

6 个答案:

答案 0 :(得分:52)

以下是原始接受的答案:laravel-4

findOrFail中已有方法Laravel,当使用此方法时,它会在失败时抛出ModelNotFoundException但在您的情况下,您可以通过在模型中创建方法来执行此操作例如,如果您有User模型,那么您只需将此函数放入模型中

// Put this in any model and use
// Modelname::findOrCreate($id);
public static function findOrCreate($id)
{
    $obj = static::find($id);
    return $obj ?: new static;
}

从控制器中,您可以使用

$user =  User::findOrCreate(5);
$user->first_name = 'Jhon';
$user->last_name = 'Doe';
$user->save();

如果id od 5的用户是exixts,那么它将被更新,否则将创建一个新用户,但id将是last_user_id + 1(自动递增)。

这是另一种做同样事情的方法:

public function scopeFindOrCreate($query, $id)
{
    $obj = $query->find($id);
    return $obj ?: new static;
}

您可以在模型中使用scope,而不是创建静态方法,因此Model中的方法将为scopeMethodName并调用Model::methodName(),与您相同在静态方法中做了,例如

$user =  User::findOrCreate(5);

更新

firstOrCreate中提供了Laravel 5x,答案太旧了,Laravel-4.02013的答案已经过了。

在Laravel 5.3中,firstOrCreate方法具有以下声明:

public function firstOrCreate(array $attributes, array $values = [])

这意味着您可以像这样使用它:

User::firstOrCreate(['email' => $email], ['name' => $name]);

用户的存在只会通过电子邮件进行检查,但在创建时,新记录将保存电子邮件和姓名。

API Docs

答案 1 :(得分:27)

或者,在这种情况下,您也可以使用Laravel的函数并搜索id作为属性,即

$user = User::firstOrCreate(['id' => $id]);

答案 2 :(得分:10)

Laravel 4模型具有内置的findOrNew方法,可以满足您的需求:

$user = User::findOrNew($id);

答案 3 :(得分:6)

在Laravel 5中:
您可以使用两种方法通过批量分配属性来创建模型:firstOrCreatefirstOrNew
firstOrCreate方法将尝试使用给定的列/值对定位数据库记录。如果在数据库中找不到该模型,则将使用给定属性插入记录 像firstOrNew这样的firstOrCreate方法将尝试在数据库中查找与给定属性匹配的记录。但是,如果未找到模型,则会返回新模型实例。请注意,firstOrNew返回的模型尚未保留到数据库中。您需要手动调用save来保存它:

// Retrieve the flight by the attributes, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

// Retrieve the flight by the attributes, or instantiate a new instance...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

答案 4 :(得分:6)

根据主键 ID

查找或新建
$user = User::findOrNew($id); // if exist then update else insert
$user->name= $data['full_name'];
$user->save();

基于非主键单一字段

的First或New
// get the record where field_name=value else insert new record
$user = User::firstOrNew(['field_name'=>'value']); 
$user->name= $data['full_name'];
$user->save();

基于非主键多字段

的First或New
// get the record where field_name1=value1 and field_name2=value2, else insert new record
$user = User::firstOrNew(['field_name1'=>'value1','field_name2'=>'value2']);
$user->name= $data['full_name'];
$user->save();

答案 5 :(得分:2)

您可以使用firstOrCreate(它使用Laravel 4.2)

$bucketUser = BucketUser::firstOrCreate([
    'bucket_id' => '1',
    'user_id'   => '2',
]);

返回找到的实例或新实例。