简体   繁体   English

在Laravel 5中无需手动分配外键就无法关联模型

[英]Unable to associate models without manually assigning the foreign key in Laravel 5

I'm running into an issue when trying to associate a child model to a parent in Laravel 5. 尝试在Laravel 5中将子模型与父模型关联时遇到问题。

I see in the documentation under the Inserting Related Models 's "Associating Models (Belongs To)" section that I should be able to: 在文档中“ 插入相关模型 ”的“关联模型(属于)”部分下,我应该能够:

  • Create a child model instance: $comment = new Comment(['message' => 'A new comment.']); 创建一个子模型实例: $comment = new Comment(['message' => 'A new comment.']);
  • Get the parent record: $post = Post::find(1); 获取父记录: $post = Post::find(1);
  • Use the parent record's association method to save the child which should automatically relate it to the parent: $comment = $post->comments()->save($comment); 使用父记录的关联方法来保存子级,该子级应自动将其与父级相关联: $comment = $post->comments()->save($comment);

This makes sense to me conceptually, the problem I'm having is creating the child record without manually assigning the parent's id as a foreign key. 从概念上讲,这对我来说很有意义,我遇到的问题是创建子记录而没有手动将父级ID分配为外键。

In my project, I have have a parent table Accounts and a child table Events . 在我的项目中,我有一个父表Accounts和一个子表Events The Events schema has a foreign key constraint assigned for the Accounts id: 事件模式具有为帐户ID分配的外键约束:

Schema::create('events', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('account_id')->unsigned();
    $table->foreign('account_id')->references('id')->on('accounts');
    $table->timestamp('date_of_donation');
    $table->timestamp('date_last_donation_letter_sent');
    $table->timestamps();
});

So when I go to create the Events instance that I'm planning on associating to the parent Accounts I get an exception thrown: 因此,当我创建打算与父帐户关联的Events实例时,会抛出异常:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'account_id' cannot be null (SQL: insert into events ( date_of_donation , date_last_donation_letter_sent , account_id , updated_at , created_at ) values (2015-05-16, , , 2015-05-16 17:35:36, 2015-05-16 17:35:36)) SQLSTATE [23000]:违反完整性约束:1048列“ account_id”不能为空(SQL:插入eventsdate_of_donationdate_last_donation_letter_sentaccount_idupdated_atcreated_at )值(2015-05-16 date_last_donation_letter_sent 2015-05-16 17 :35:36,2015-05-16 17:35:36))

I understand why the error is thrown because I'm not giving the Events instance a foreign key value. 我了解为什么会引发错误,因为我没有给Events实例提供外键值。

I can get around it by getting the Accounts record first and creating the Events instance like so: 我可以通过首先获取Accounts记录并创建Events实例来解决该问题,如下所示:

$account = $accounts->findOrFail($id);
$event = $events->create(['account_id' => $account->id, ...]);

But it seems like the whole point of the "Associating Models (Belongs To)" section is so that you don't have to do this. 但这似乎是“关联模型(属于)”部分的全部要点,因此您不必这样做。

Am I missing or misunderstanding something about how the associating functionality is supposed to work? 我是否缺少或误解了有关关联功能应该如何工作的信息?

Update 更新资料

Here's my Account model: 这是我的Account模型:

<?php namespace Hub;

use Illuminate\Database\Eloquent\Model;

class Account extends Model {

    protected $fillable =[
        'first_name',
        'last_name',
        'display_name',
        'email',
        'zipcode',
        'phone_number'
    ];

    public function donationEvents(){
        return $this->hasMany('Hub\donationEvent');
    }


}

And my Event model: 而我的Event模型:

<?php namespace Hub;

use Illuminate\Database\Eloquent\Model;

class Event extends Model {

    protected $fillable = [
        'account_id',
        'date_of_donation',
        'date_last_donation_letter_sent'
    ];

    public function donationItems(){
        return $this->hasMany('Hub\DonationItem');
    }

    public function account(){
        return $this->belongsTo('Hub\Account');
    }
}

Also, here's the code that triggers the error: 另外,这是触发错误的代码:

Route::get('dev2', function ( Hub\Account $accounts, Hub\Event $events){
    $account = $accounts->findOrFail(1);

    // This is where I'm trying to create the child record but I get the exception
    $event = $events->create(['date_of_donation' => '2015-05-16', 'date_of_last_donation_letter_sent' => '']);

    $event = $account->events()->save($event);
    return [$account, $event];

});

The thing is, create() instantiates a new model and directly saves it. 问题是, create()实例化一个新模型并直接保存它。 So you actually save it twice. 因此,您实际上将其保存了两次。 However the first time there is no foreign key set. 但是,第一次没有设置外键。

Instead of create() use fill() to set all the values without saving: 代替create()使用fill()设置所有值而不保存:

$event = $events->fill(['date_of_donation' => '2015-05-16', 'date_of_last_donation_letter_sent' => '']);

Or you can use the constructor as well (I personally prefer this solution) 或者您也可以使用构造函数(我个人更喜欢此解决方案)

$event = new Event(['date_of_donation' => '2015-05-16', 'date_of_last_donation_letter_sent' => '']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM