atastrophic
atastrophic

Reputation: 3143

Updating Related Model (foreign key) in Laravel & Eloquent

There are two tables, Language & Text with a one-to-many relationship where the Text receives foreign key of Language table.

I have set up models & relationships properly & the retrieval of models works just fine.

How can I associate Language entity to certain existing Text records.

I have tried fetching some Text records and inserting them into Language using

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

where texts() returns hasMany('Text').

The error returned by laravel is ..

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

I'm not sure why Laravel is trying to use block quotes ` instead of ' for values..

Plus, it seems to be inserting new records instead of updating existing ..

Upvotes: 1

Views: 3479

Answers (3)

hungtran273
hungtran273

Reputation: 1357

Child.php

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

Parent.php

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

Update foreign key:

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

More info: https://meigwilym.com/family-fortunes-saving-and-updating-laravel-relations/

Upvotes: 0

HiTech
HiTech

Reputation: 305

In Laravel 4 use whereIn method

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

Upvotes: 0

user1669496
user1669496

Reputation: 33148

Try $language->texts()->associate($textRecords);

Upvotes: 2

Related Questions