I'm facing a really strange issue in a hasMany
relationship, It was not returning me anything so I started digging to try to find something
so now I have this code
echo $item->id ."<br />"; var_dump($item->menuMenuCategories()->getParent()->getKey()); echo "<br>"; var_dump($item->menuMenuCategories()->getParent()->getKeyName());
echo "
";$query = $item->menuMenuCategories()->getBaseQuery()->toSql(); echo $query ."<br />";
and the result is this:
4 string(1) "4"
string(2) "id"
select * from
GS_menu_menu_categories
whereGS_menu_menu_categories
.deleted_at
is null andGS_menu_menu_categories
.item_id
= ?select * from
GS_menu_menu_categories
whereGS_menu_menu_categories
.deleted_at
is null andGS_menu_menu_categories
.item_id
= ?
Can you see the item_id = ? ??
That why it is not returning me anything..
My model has the relationship defined this way:
public function menuMenuCategories(){ return $this->hasMany('MenuMenuCategory','item_id'); }
Any idea on why it isn't working? I have the hasMany relationship in a thousand places and never had this problem..
Thank you
Make sure you have provided everything properly; for example, item_id
should be in the related table GS_menu_menu_categories
and it should contain an id
primary key, or you may specify both if they are different, i.e:
class Item extends Eloquent {
protected $table = 'items';
public function menuMenuCategories(){
// if GS_menu_menu_categories has "the_id" instead of "id" as pk
return $this->hasMany('MenuMenuCategory','item_id', 'the_id');
}
}
Use it like:
$item = Item::with('menuMenuCategories')->find(1); // the item with id 1
Use following to access the related collection of models
$menuMenuCategories = $item->menuMenuCategories;
$item->menuMenuCategories->first(); // get the first one
$item->menuMenuCategories->get(1); // get the second one
$item->menuMenuCategories->get(2); // get the third one
Don't use this:
$item->menuMenuCategories()
So, for example, in a view (non-blade
):
foreach($item->menuMenuCategories as $category) {
echo $category->propertyName;
}