Laravel framework eloquent relationship query

faizan-ahmed

Feb 1st, 2019 10:30 AM

2

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'); }

syedreza

Aug 1st, 2022 10:15 AM

Try to correct the relationship. For example, BuisnessInfo has many ElectricityInfo. So in BuisnessInfo model add-> public function electricity() { return $this->hasMany('App\Models\ElectricityInfo', 'business_info_id', 'id'); }

*Here business_info_id is a foreign field for electricity_infos table $table->foreign('business_info_id ')->references('id')->on('buisness_infos');