简体   繁体   English

如何从Laravel中的两个表联接并获取数据?

[英]How to join and get data from two tables in laravel?

I'm working on a laravel project. 我正在做一个laravel项目。 I'v got two tables : company, Prouct 我有两个桌子:company,Prouct
Every company has many products . 每个公司都有很多产品。 I want to display the company name and logo along with the product details . 我想显示公司名称和徽标以及产品详细信息。

class Company extends Model
{

// 
    public function products()
    {
        return $this->hasMany('System\Product','company_id');
    }
}

...........
    class Product extends Model
{
   public function company()
    {
      return $this->belongsTo('Systems\Company','id'); 
        }
}

.......... ..........

company_table
id   company_name  company_logo
 1       MDE        image.png
procut_table
id  product_name  price  company_id
1     7-up         200      1

How I want to dispaly it? 我要如何分散它?

I want to display it like this : 我想这样显示:

Product_name
price
company_name
company_logo

How can I write a query in laravel to give me this result? 如何在laravel中写一个查询给我这个结果? ............... ......

You need to use join , You can use the following query 您需要使用join ,可以使用以下查询

$result = DB::table('Product')->join('Company', 'Product.company_id', '=', 'Company.id')->get();

To get your result 得到你的结果

You can call for your products and load it's relation company . 您可以致电您的产品并加载它的联系company

$products = Product::with('company')->get();

Then you can access the company of each product 然后您可以访问每个产品的公司

@foreach($products as $product)
    {{$product->name}}<br/>
    {{$product->price}}<br/>
    {{$product->company->name}}<br/>
    {{$product->company->logo}}<br/>
@endforeach
    class Company extends Model
    {

        public function products()
        {
            return $this->hasMany('System\Product','company_id','id');
        }
    }


    class Product extends Model
    {
       public function company()
        {
          return $this->belongsTo('Systems\Company','company_id','id'); 
            }
    }

In your controller , you can get like this. 在您的控制器中 ,您可以像这样。

$products = Product::with('company')->get();

    foreach ($products as $product) {
       echo $product->company->name; //MDE
       echo $product->company->company_logo; //image.png
       echo $product->price; //200

    }

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

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