第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從laravel 5中的兩個相關(guān)表中獲取數(shù)據(jù)

如何從laravel 5中的兩個相關(guān)表中獲取數(shù)據(jù)

PHP
泛舟湖上清波郎朗 2021-11-26 17:55:27
我有 3 個安裝了外鍵的表。customers {customer_id, customer_name}products {product_id, product_name}customer_products {id, customer_id (foreignkey), product_id (foreignkey)}我的控制器代碼:$CustomerProducts = ModelName::where('customer_id', 'somevalue')->Join('customer_products', 'product_id', '=', 'customer_id')       ->get();我的型號代碼:class ModelName extends Model { protected $table = 'hd_products';public $primaryKey = 'id'; }我的代碼有什么問題,因?yàn)槲业玫搅隋e誤的結(jié)果。我想展示客戶信息及其相關(guān)產(chǎn)品。
查看完整描述

2 回答

?
互換的青春

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個贊

這就是 Laravel 讓生活變得輕松的地方。通過在模型上添加關(guān)系,您可以通過預(yù)先加載簡單地調(diào)用關(guān)系。你不需要join,你可以只拉關(guān)系。所以


在您的Customer 模型上,設(shè)置產(chǎn)品關(guān)系(您看起來擁有正確的多對多數(shù)據(jù)庫結(jié)構(gòu)):


 public function products(){

    return $this->belongsToMany("\App\Product");

 }

然后在您的Controller 中,當(dāng)您加載客戶時,您可以同時抓取產(chǎn)品:


$customer = Customer::with("products")->first();

我只是以第一個客戶為例 - 如果您愿意,您可以獲取所有客戶并循環(huán)使用客戶和產(chǎn)品。


最后,當(dāng)您想在刀片視圖中調(diào)用數(shù)據(jù)時,您可以通過鏈接$customer模型來訪問它。:


{{ $customer->products->first()->name }}

如果您想在刀片視圖中循環(huán)瀏覽客戶上的產(chǎn)品:


@foreach($customer->products as $product){}

而且,您仍然擁有 $customer 的主要數(shù)據(jù):


$customer->name // Etc.

HTH


查看完整回答
反對 回復(fù) 2021-11-26
?
汪汪一只貓

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個贊

如果要顯示客戶信息及其相關(guān)產(chǎn)品,則必須從表中選擇數(shù)據(jù)。


在您的代碼中,在控制器中,從您添加的所有表中獲取所有數(shù)據(jù):


->select(['customers.*' ,'products.*' ,'customer_products.*'])->get();

并編輯 join 語句,使控制器如下所示:


$CustomerProducts= DB::table('customer_products')

      ->join('customers','customers.customer_id','customer_products.customer_id')

      ->join('products','products.product_id','customer_products.product_id')

      ->select(['customers.*' ,'products.*' ,'customer_products.*'])

      ->get();

不要忘記添加(如果沒有添加)


use DB;

在你的文件的開頭(在命名空間區(qū)域或?qū)雲(yún)^(qū)域),所以它是這樣的:


namespace App\Http\Controllers;

use DB;

use App\ //"your_file";

use Illuminate\Http\Request;

希望這有幫助:)


查看完整回答
反對 回復(fù) 2021-11-26
  • 2 回答
  • 0 關(guān)注
  • 187 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號