Reputation: 131
I have an Artist model and an Item model.
class Artist extends Model {
protected $table = 'contactsdata';
protected $primaryKey = 'c_id';
public function artworks() {
return $this->hasMany('App\Item', 'c_id', 'c_id');
}
}
class Item extends Model {
protected $table = 'stock';
protected $primaryKey = 's_id';
}
In my ArtistsController I have this code:
public function show($id)
{
DB::enableQueryLog();
$artist = Artist::find($id);
$artworks = Artist::find($id)->artworks;
dd(DB::getQueryLog(), $artworks->toArray());
}
In the database there are many records qualifying to populate $artworks. But this is my dd() output:
array:2 [▼
0 => array:3 [▼
"query" => "select * from `contactsdata` where `contactsdata`.`c_id` = ? limit 1"
"bindings" => array:1 [▼
0 => "2242"
]
"time" => 2.59
]
1 => array:3 [▼
"query" => "select * from `stock` where `stock`.`c_id` is null"
"bindings" => []
"time" => 2.52
]
]
[]
For some reason the if field (c_id) is set to null for the second or relationship query. Any ideas? Help!
Upvotes: 1
Views: 1060
Reputation: 131
Thanks all. I have solved this myself. Eloquent relationship field names are case sensitive. For some reason my database table has all its fields (in its scheme) named in UPPER CASE. Once I changed the hasMany parameters to 'C_ID', 'C_ID' everything worked just fine.
So worth knowing that Eloquent relationship field names are CASE SENSITIVE.
Upvotes: 1
Reputation: 111829
To achieve what you want, you should rather use here:
$artist = Artist::find($id);
$artworks = $artist->artworks;
instead of:
$artist = Artist::find($id);
$artworks = Artist::find($id)->artworks;
Upvotes: 1