Home > Back-end >  Laravel 9 - specular model relations not working
Laravel 9 - specular model relations not working

Time:10-01

i can't figure out why my eloquent relationship is not working. I have the grid and details tables related (es. grid.id = details.order_id). This works for first 2 tables but not for other 2 that are almost a copy of the first.

Working relationship code :

OrderGrid model:

use HasFactory;

protected $table = 'orders_grid';

protected $fillable = [
    'user_id',
     // more data
];

public function order_detail()
{
    return $this->hasMany('App\Models\OrderDetail');
}

OrderDetail model:

    use HasFactory;

protected $table = 'orders_detail';

protected $fillable = [
    'order_id',
    // more data
];

public function order_grid()
{
    return $this->belongsTo('App\Models\OrderGrid', 'order_id', 'id');
}

In controller

$data_details = OrderDetail::where('order_id', $id)->get();

in view

$data_details->first()->order_grid->id
// so i can get the ID from the related table

enter image description here

Now i have two more very similar models which relations are not working:

OrderGrid model 2

use HasFactory;

protected $table = 'orders_grid_jde';

protected $fillable = [
    'total_order',
    // more data
];

public function detail_jde()
{
    return $this->hasMany('App\Models\OrderDetailJde');
}

OrderDetail model 2 :

    use HasFactory;

protected $table = 'orders_detail_jde';

protected $fillable = [
    'order_jde_id',
];

public function grid_jde()
{
    return $this->belongsTo('App\Models\OrderGridJde', 'order_jde_id', 'id');
}

In controller:

$data_details = OrderDetailJde::where('order_jde_id', $id)->get();

In view:

$data_details->first()->order_jde_id->id

This is not working, if i dump($data_details->first()) relations is empty array, not as in the screen shown before

Another weird behaviour on working relation: if i dump $data_details->first() in the controller i don't see the relation, but if i do it in view it shows as in the screen.

Sorry for the long post, tried to be understandble as possible

CodePudding user response:

In the view where you have the error, you are accessing the directly to the field named order_jde_id instead of the relationship grid_jde.

Tips:

You should eager load the relationships if you are planning to use these in the view.

$books = Book::with('author')->get();

https://laravel.com/docs/9.x/eloquent-relationships#eager-loading

CodePudding user response:

In your Controller call the relation like this:

$data_details = OrderDetailJde::where('order_jde_id', $id)->with("grid_jde")->get();

In view: $data_details->first()

It will give all the detils.

It should work now.

  • Related