I want to Use firstOrCreate Function of Eloquent. The relevant part of my Data are Athletes belonging to a Nation and Nation holding many Athletes. (One to Many Relation)
class Athlete extends Model
{
public $timestamps = false;
protected $fillable = ['firstname', 'lastname', 'nation'];
.....
public function nation()
{
return $this->belongsTo('App\Nation');
}
}
and
class Nation extends Model
{
public $timestamps = false;
...
public function athletes()
{
return $this->hasMany('App\Athlete');
}
}
How can I use firstOrCreate if I also have to check for the nation?
Neither
$ath = Athlete::firstOrCreate(['nation_id'=>$nation->id, 'lastname'=>$nn, 'sex'=>$sex, 'firstname'=>$vn] );
nor
$ath = Athlete::firstOrCreate(['nation'=>$nation, 'lastname'=>$nn, 'sex'=>$sex, 'firstname'=>$vn] );
work.
First case:
"Nation_id doesn't have a default value"
Second case:
Laravel tries to build a WHERE statement with the passed object, which obviously doesn't work.
Can I use firstOrCreate here?
THANK YOU.