在Laravel&Eloquent中更新相关模型(外键)


Updating Related Model (foreign key) in Laravel & Eloquent

有两个表,LanguageText具有一对多关系,其中Text接收Language表的外键。

我已经正确设置了模型和关系,模型的检索工作正常。

如何将Language实体关联到某些现有Text记录。

我尝试获取一些Text记录并将它们插入Language

使用
$language = Language::find(1);
$textRecords = TextRecord::where('id', 'IN', array(1,2,3,4,5,6,7))->get();
$language->texts()->insert($textRecords);

texts()返回的地方hasMany('Text').

拉维尔返回的错误是..

Unknown column '0' in 'field list' (SQL: insert into `ayah_text` (`0`, `1`....

我不确定为什么Laravel试图使用块引号'而不是'作为值。

另外,它似乎正在插入新记录而不是更新现有记录..

尝试$language->texts()->associate($textRecords);

在 Laravel 4 中使用 whereIn 方法

$textRecords = TextRecord::whereIn('id', array(1,2,3,4,5,6,7))->get();

Child.php

public function parent() {
    return $this->belongsTo(Parent::class);
}

父母.php

public function children() {
    return $this->hasMany(Child::class);
}

更新外键:

// updates $child->parent_id
$parent = Parent::find($your_id);
$child->parent()->associate($parent);
$child->save();

更多信息: https://meigwilym.com/family-fortunes-saving-and-updating-laravel-relations/