user1805218
user1805218

Reputation: 15

Laravel belongsToMany Intermediary Table

I have 3 tables that look like this:

Market

Market_to_City

City

and a model that looks like:

class Market extends Eloquent {
    protected $table = 'Market';

    public function citys() {
        return $this->belongsToMany('City', 'Market_to_City', 'market_id', 'city_id');
    }
}

Each market has many cities mapped through the Market_to_City table. The citys method should return a collection of cities that are related to a market. This however returns an empty collection every time, am I using the correct model relationship?

Upvotes: 0

Views: 496

Answers (1)

Tomas Buteler
Tomas Buteler

Reputation: 4117

Your method looks correct. However, note that you have named it citys instead of cities, which may or may not have been a typo while posting your question here. The correct plural form of city is cities and you should correct it because Laravel often uses automatic pluralization and assumes you'll get your English right.

Also, your model is called Market, while in the comments you're calling GTM_Market.

It's also assumed that the Market object does not have a cities property, so it will successfully fall back to the method which then fires the relationship query. If you happen to declare the property beforehand, Laravel will never reach the method.

class Market extends Eloquent {

    public $cities = 'Foo';

    public function cities()
    {
        return $this->belongsToMany('City');
    }
}

$market = Market::find(205);

echo $market->cities; // Echoes 'Foo' instead of the relationship.

Lastly, with all of the above taken care of, you'd be able to eager-load the relationship like so:

Market::with('cities')->find(205);

Upvotes: 3

Related Questions