TransWikia.com

How to use has one through in laravel?

Stack Overflow Asked by ahz on September 17, 2020

I want to ask, there are three tables I’ve created, the following tables is bellow

brands

  • brand_id
  • brand_name

motorcycles

  • motorcycle_id
  • brand_id
  • motorcycle_name

purchases

  • purchase_id
  • motorcycle_id
  • purchase_price
  • purchase_location

How to get data purchase_id, motorcycle_name and brand_name ?
I tried to use hasOneThrough() with model like this :

class Purchase extends Model
{
    protected $primaryKey = 'purchase_id';

    public function motorcycleBrand(){
        return $this->hasOneThrough(Brand::class,Motorcycle::class,'brand_id','brand_id');
    }
}

And this is code inside controller :

$data = Purchase::->with(['motorcycleBrand', 'motorcycle'])->get();
return response()->json($data);

But it’s not working, motorcycle data is showing but brand data is not showing (null).
Is it possible if I want to get data as I want ? If possible how to get it ?
Thank you..

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP