简体   繁体   English

如何使用另一个表中的ID从另一个表中获取数据

[英]How to get data from another table using ID from another table

I would like to get a data from a table to another table using it's primary key. 我想使用它的主键从一个表到另一个表获取数据。

products_table:
id   name    type_id  date_added
 1   item1      2        1234
 2   item2      2        5678
 3   item3      1        0000

product_type_table:
id  type_name
 1    type1
 2    type2
 3    type3

I am querying the first table using this code: 我正在使用此代码查询第一个表:

Products::select('name','type_id')->where('id',$id)->get()

Now, how do I automatically get the type_name from the product_type_table using the type_id from the products_table? 现在,如何使用products_table中的type_id从product_type_table中自动获得type_name?

As Jack Skeletron pointed out, the Laravel documentation has examples for joining 2 or multiple tables . 正如Jack Skeletron所指出的那样,Laravel文档中有连接2个或多个表的示例

In your case 就你而言

$products = DB::table('products_table')
    ->join('product_type_table', 'products_table.type_id', '=', 'product_type_table.type_id')
    ->select('products_table.name, products_table.type_id')
    ->where('id', $id)
    ->get();

you can use left join. 您可以使用左联接。

DB::table('product_type_table')
        ->leftJoin('products_table', 'product_type_table.id', '=', 'products_table.type_id ')->where('product_type_table.id',$id)
        ->get();

In Product Model add Below code for joining 2 tables: 在产品模型中,添加以下代码以连接2个表:

use App\Models\ProductType;

public function type()
{
 return $this->belongsTo(ProductType::class);
}

and change the line: 并更改行:

Products::select('name','type_id')->where('id',$id)->get()

to

Products::select('name','type_id')->with(['type' => function($q){
    return $q->select('type_name');
}])->where('id',$id)->get()

Hope this works for you. 希望这对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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