thedevdojo / chatter

Chatter is a Simple Laravel Forum Package
https://devdojo.com/forums
MIT License
898 stars 294 forks source link

Laravel framework eloquent relationship query #234

Open faizanahmed786 opened 5 years ago

faizanahmed786 commented 5 years ago

I have created relationship between 4 tables.

This are my models:

User BusinessInfo ElectrcityInfo GasInfo This are the primery keys that I am using in my tables:

user_id (to get login users data from BusinessInfo) contract_id (This also exists in BusinessInfo I am use it to get data from the other two tables for specific records) Now I want to get all login users data from BusinessInfo table and each BusinessInfo row has its own 1 row data from ElectricityInfo and GasInfo.

When I am use contract_id in model its give me relationship result null. When it is on user_id its display only 1 ElectrcityInfo with all records.

Controller

$user = Auth::user(); $business = BusinessInfo::where('user_id', $user->id)->first(); $data = $business->electricity()->paginate(6);

return view('Pages.MySite', ['data' => $data]); BusinessInfo Model

protected $primaryKey = 'contract_id'; public $table = "business_info"; protected $guarded = []; public $timestamps = false;

public function electricity() { return $this->belongsTo('App\Models\ElectricityInfo', 'contract_id'); }

public function gas() { return $this->belongsTo('App\Models\GasInfo', 'contract_id'); }