简体   繁体   中英

How to get data from the foreign key in joined table in laravel 5.8

I want to get the details of products in the products table by calling it in the purchase_orders table in laravel5.8.

I try to use inner join but as its result its just values of numbers

 $POs = DB::table('purchase_orders')
            ->join('products', 'purchase_orders.prod_id', '=', 'products.id')
            ->select('purchase_orders.id as id', 'products.name as name', 'products.cat_id as cat', 'products.size_id as size', 'products.price as price', 'purchase_orders.quant as quant', 'purchase_orders.total as total', 'purchase_orders.created_at as req_date')
            ->orderBy('purchase_orders.id','DESC')
            ->get();

Here are the 2 table and the result.

products table

在此处输入图像描述

purchase_orders

在此处输入图像描述

result

在此处输入图像描述

Create a relationship in PurchaseOrders Model :

public function products()
{
    return $this->hasMany('App\Models\Product','id','prod_id');
}

You can call the result by:

$res = PurchaseOrder::find($id);
foreach($res->products as $product)
{
  echo $product->name;
}

Using join:

 $POs = DB::table('purchase_orders')
        ->join('products', 'purchase_orders.prod_id', '=', 'products.id')
        ->select('products.*','purchase_orders.id as purchase_id','purchase_orders.total','purchase_orders.status')
        ->orderBy('purchase_orders.id','DESC')
        ->get();

if you want categories table too, add another join function.

Try this for a relationship

public function products()

{

return $this->hasMany('App\Models\Product','prod_id','id');

}

public function products()

{

return $this->hasMany('App\Models\Product','prod_id','id');

}

To out put relationship data is like this

$variable->product->name

or

$variable->product['name']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM