mardi 11 décembre 2018

Can eloquent ignore irrelevant data in Laravel 5.7

This is basically the same question as this here from 2013. Except the answer doesn't work for me.

I have a Model App\Post:

 class Post extends Model
 {
   protected $fillable = ['title'];
   // This Model doesn't contain an 'authorname' field
   public function author()
   {
     return $this->belongsTo('App\Author');
   }
 }

and a Model App\Author:

 class Author extends Model
 {
   protected $fillable = ['name'];

   public function posts()
   {
     return $this->hasMany('App\Post');
   }
 }

And an array I want to save to that Model:

$posts = [
   ['title'=>'one post', 'authorname' => 'Mickey'],
   ['title'=>'another post', 'authorname' => 'Minny'],
];

foreach($posts as $post){
   $authorModel=App\Author::firstOrCreate(['name'=>$post['authorname']]);
   App\Post::create($post)->author()->associate($authorModel)->save();
}

According to this question, that should work, but I get an

SQL error 42522: Column not found: 1054 Unknown column 'authorname' in 'field list'

which suggests Laravel forwards the whole array to mySQL. Is there a way to make this work without unsetting the authorname key?

Obviously this is a simpified version of what I want to do and keeping track of what to unset seems unnecessary - as would be assigning all array keys to their respective database fields manually.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire