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

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;
希望這有幫助:)
- 2 回答
- 0 關(guān)注
- 187 瀏覽
添加回答
舉報(bào)