Laravel 5雄辩无法保存一对多的相关模型

时间:2015-04-21 16:24:23

标签: eloquent laravel-5

该应用程序具有以下模型: NotificationParent.php

class NotificationParent extends Model{
    use SoftDeletes;
    protected $table = 'NotificationParent';
    protected $primaryKey = 'notificationparent_id';
    protected $fillable = ['category', 'description'];
    protected $dates = ['deleted_at'];

    public function notifications()
    {
        return $this->hasMany('App\Models\Notification', 'notificationparent_id', 'notification_id');
   }

}

Notification.php

class Notification extends Model{
    use SoftDeletes;
    protected $table = 'Notification';
    protected $primaryKey = 'notification_id';
    protected $fillable = ['notificationparent_id', 'title', 'description', 'link'];
    protected $dates = ['deleted_at'];


    public function notificationParent()
    {
        return $this->hasOne('App\Models\NotificationParent', 'notification_id', 'notificationparent_id');
    }
}

我无法使用以下代码保存通知:

$notification = new Notification(['title' => 'access denied', 'description' => 'access denied for user one' , 'link' => 'http----']);
$notificationParent = NotificationParent::where('category', '=', 'admin')->first();
$notificationParent->notifications()->save($notification);

即使$ notificationParent不为null,也会出错:

SQLSTATE[23000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Cannot insert the value NULL into column 'notificationparent_id', table 'five.dbo.Notification'; column does not allow nulls. INSERT fails. (SQL: insert into [Notification] ([title], [description], [link], [notificationparent_id], [updated_at], [created_at]) values (access denied, access denied for user one, http---, , 2015-04-21 16:02:57.000, 2015-04-21 16:02:57.000))

1 个答案:

答案 0 :(得分:1)

hasOne用于一对一的关系。 hasMany的逆是belongsTo