Pregunta

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 ..

¿Fue útil?

Solución

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

Otros consejos

In Laravel 4 use whereIn method

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

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/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top