Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FutureWeb's avatar

Multiple table db query help

Hi Larafolks,

i have 3 tables mobiles, deals and tariffs

Mobiles contains info about the handset name, make, colour and popularity

tariffs contains information about the tariff inclusive minutes, texts, data, monthly_cost and the network which offers the tariff

Deals contains any incentive information such as x months free line rental or a free gift and links mobiles to tariffs on mobile_id and tarrif_id it also contains a popularity field to show how popular a specific deal is.

What I a trying to do is pull the 6 most popular mobiles (handsets) and display the most popular deal for each and associated tariff info how can I do that in my controller old school I would have used a dirty nested query but so far I have:

$mobiles=\Mobile::limit($limit)->join('deals', 'mobiles.id','=', 'deals.mobile_id')->join('tariffs','tariffs.name', '=','deals.tariff_id')->orderBy('mobiles.popularity','DESC')->get()->toArray();

any help would be greatly appreciated. :)

0 likes
1 reply
NoorDeen's avatar

first you must set the relationships in your Entities (Models) like this :


class Mobile extends Eloquent { public function deals() { return $this->hasMany('Deal'); } } class Deal extends Eloquent { public function tariff() { return $this->hasOne('Tariff'); } }

then use this :

$mobiles = Mobile::with('deals','deals.tariff')->get();

Please or to participate in this conversation.