Laravel Eloquent :: firstOrCreate问题

时间:2014-06-01 07:09:48

标签: php laravel eloquent

好的,所以我试图在另一个Eloquent模型中使用Eloquent方法“firstOrCreate”。

FriendRequest Eloquent

class FriendRequest extends Eloquent {

/**
 * The database table used by the model.
 *
 * @var string
 */
public $table = 'requests';
protected $guarded = array('id');
protected $softDelete = true;

public function friend() {
    return $this->hasOne('User', 'id', 'friend_id');
}

public function user() {
    return $this->hasOne('User', 'id', 'user_id');
}

public function accept() {

    // FIRST YOU MUST MARK REQUEST AS ACCEPTED
    // THEN SOFT DELETE REQUEST SO IT DOESN'T
    // SHOW UP AS ACTIVE FRIEND REQUEST
    $this->accepted = '1';
    $this->save();

    // CREATE FRIENDSHIP USER -> REQUESTED
    $friend             =   Friend::firstOrNew(array('user_id' => Auth::user()->id, 'friend_id' => $this->friend_id));
    $friend->save();

    // CREATE FRIENDSHIP REQUESTED -> USER
    $friend2             =   Friend::firstOrNew(array('user_id' => $this->friend_id, 'friend_id' => Auth::user()->id));
    $friend2->save();

    // SOFT DELETE REQUEST BEING MARKED ACCEPTED
    $status = $this->delete();

    if (!$status):
        return false;
    else:
        return true;
    endif;

}

}

我已经尝试了firstOrCreate和firstOrNew,如图所示,但是数组中给出的'friend_id'和'user_id'都设置为'0'。

行或索引没有默认值。

这是朋友雄辩的模型

class Friend extends Eloquent {

/**
 * The database table used by the model.
 *
 * @var string
 */
public $table = 'friends';
protected $guarded = array('id');

public function user() {
    return $this->hasOne('User', 'id', 'user_id');
}

public function friend() {
    return $this->hasOne('User', 'id', 'friend_id');
}

}

2 个答案:

答案 0 :(得分:3)

create()方法执行批量分配,这是一个很大的安全问题,因此Laravel可以对其进行保护。在内部,它已经保护= [' *'],因此您的所有列都将受到保护,不会进行批量分配。你有一些选择:

设置模型的可填写列:

class User extends Eloquent {

    protected $fillable = array('first_name', 'last_name', 'email');

}

或者只设置你想要守卫的那些:

class User extends Eloquent {

  protected $guarded = array('password');

}

您可能会自行承担风险:

class User extends Eloquent {

    protected $guarded = array();

}

还有关于firstorcreate和firstornew之间的区别:

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

您也可以浏览Facade并使用以下内容:

 class Settings extends Eloquent
 {
    protected $table = 'settings';
    protected $primaryKey = 'name';

     public static function get($settingName)
     {
         return Settings::firstOrCreate(array('name' => $settingName));
      }
}

答案 1 :(得分:0)

我相信你应该将accept()功能放在你的一个控制器而不是模型中。我不确定你是如何以及在何处调用此功能,但我认为它位于错误的位置。