llioor's avatar

with() and select() not working together

I have many to many relation like this:

On Campaign model:

public function categories() {
    return $this->belongsToMany('App\Categories_reseller', 'campaigns_categories', 'campaign_id', 'category_id')->withTimestamps();
    }

On Categories_reseller model:

 public function campaigns() {
    return $this->belongsToMany('App\Campaigns', 'campaigns_categories', 'category_id', 'campaign_id')->withTimestamps();
    }

When I do this I receive categories collection:

$campaign = \App\Campaign::getByToken($token)
            ->with('categories')
            ->firstOrFail();

When I do this, I receive empty collection in categories items relation:

$campaign = \App\Campaign::getByToken($token)
            ->select('id') // campaign ID
            ->with('categories')
            ->firstOrFail();

The getByToken function is a scope one:

 public function scopeGetByToken($query, $token) {
    return $query->where('token', $token)->where('status', 1);
    }

Any Idea what I'm doing wrong? Is it not possible to select specific values from campaigns table when using "with()"?

Thanks

0 likes
6 replies
jekinney's avatar
Level 47

Your mixing query builder and eloquent which is confusing as many functions have the same name.

With eloquent you pass an array into your get(), first() or list() to retrieve the columns you need.

firstOrFail(['id']); continue adding as you need.

kingpabel's avatar

If you use "select,with" both and wanna get relational data you need to mention relation field in select otherwise you can't get relational data

1 like
llioor's avatar

Hi @kingpabel, thanks for your answer. You are right when we are talking about hasOne relation, you need to select the FK column. The things is that I don't have FK on the table because I have other table for many to many relation.

kingpabel's avatar

@llioor if my comment helps you,please make this comment as correct answer that will helpful for another who are facing this problem

michaeldyrynda's avatar

You're getting collisions because there's an id column on both the campaigns and categories tables.

You have to be explicit about whether you want campaigns.id or categories.id in your select.

pmall's avatar

You're getting collisions because there's an id column on both the campaigns and categories tables.

No, even with eager loading it is two separate queries. The problem must be about foreign keys but I cant figure it out right now.

Also, when eager loading a relationship (non nested) of only one item, eager loading is useless.

$foo = Foo::with('bars')->first();

Fire the same number of queries (2) as :

$foo = Foo::first();
$foo->bars;

So maybe in your case it is useless.

Please or to participate in this conversation.