簡體   English   中英

使用 eloquent laravel 獲取連接表數據

[英]fetch join table data using eloquent laravel

我是 laravel 的新手,想要實現 eloquent 關系。

讓我解釋。

考慮我有 2 張桌子

產品

 product_id
 product_name
 brand_id
 price

品牌

 id
 brand_name

每個產品都有一個品牌 ID。但在 Brands 表中,沒有產品 ID。 一個brand_id 可以在多個產品行中,一個產品只有一個brand_id。 我想使用 Model.SO 在產品 model 中使用 Model.SO 從產品表加上品牌名稱對產品表的品牌 ID 的一些列進行 select 我寫道:

public function brands()
    {   
        
        return $this->hasOne('App\Brand','product_id');
    }

在 model 品牌中,我寫道:

public function products()
    {
        return $this->belongsTo('App\Product','brand_id');
    } 

現在我想要結果:

product_name
price
brand_name

如何使用 eloquent 關系在 controller 中獲取這些數據? 還有,我寫Model關系的方式,可以嗎??

您的產品 Model關系如下

public function brand(){   
    return $this->belongsTo('App\Brand','brand_id');
}
public function product(){   
    return $this->belongsTo('App\Product','product_id');
}

現在在 controller 中,您可以添加如下查詢。

$products = Product::with('brand','product')->get();
echo '<pre>'
print_r($products->toArray());
exit;

在我看來,你想要一個one-to-many關系,所以一個品牌可以有很多產品,很多產品屬於一個品牌。

產品 model:

public function brand()
{
    return $this->belongsTo('App\Brand');
}

品牌 model:

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

然后你就可以得到這樣的品牌信息:

全品牌model:

Product::first()->brand

品牌名稱:

Product::first()->brand->brand_name

文檔

一對多關系用於定義單個 model 擁有任意數量的其他模型的關系。 例如,一篇博文可能有無數條評論。

PS:

您的表列名稱對我來說沒有多大意義,為什么您在 products 上有product_id但在品牌上它只是被稱為id 為什么你有product_name但只有price 為什么不只是nameproduct_price ,所以你至少是一致的?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM