1
votes

Laravel 5.5. When I use controller like this:

$ad = Ad::get();
$category = Category::get();
$categoryItem = CategoryItem::get();

$c = CategoryItem::with('ad')->get();

I get the view like this:

{"id":1,"ad_id":"1","cat_id":"1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","ad":{"id":1,"title":"Test 1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00"}}

{"id":2,"ad_id":"2","cat_id":"2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","ad":{"id":2,"title":"Test 2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00"}}

{"id":3,"ad_id":"3","cat_id":"1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","ad":{"id":3,"title":"Test 3","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00"}}

{"id":4,"ad_id":"4","cat_id":"2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","ad":{"id":4,"title":"Test 4","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00"}}

CategoryItem model belongsTo both Ad and Category classes.

However when I try to get CategoryItem with Category, I mean like this:

$ad = Ad::get();
$category = Category::get();
$categoryItem = CategoryItem::get();

$c = CategoryItem::with('category')->get();

I get this view, with NULL beside the Category objects:

{"id":1,"ad_id":"1","cat_id":"1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","category":null}

{"id":2,"ad_id":"2","cat_id":"2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","category":null}

{"id":3,"ad_id":"3","cat_id":"1","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","category":null}

{"id":4,"ad_id":"4","cat_id":"2","created_at":"2017-10-14 00:00:00","updated_at":"2017-10-14 00:00:00","category":null}

Category model hasMany both Ads and CategoryItems.

What I actually want to do is to be able to get both Ads and Categories, it's titles, ids and other info through CategoryItem... I just need to understand this so later could change getting items by ids to getting items by slug names...

1

1 Answers

2
votes

Since you're using custom foreign key name cat_id instead of category_id, to make your code work, you need to specify the foreign key in relationship definition:

public function category()
{
    return $this->belongsTo(Category::class, 'cat_id');
}

Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. You may pass a custom key name as the second argument to the belongsTo method

https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse