2 回答
TA贡献1797条经验 获得超6个赞
这就是 Laravel 让生活变得轻松的地方。通过在模型上添加关系,您可以通过预先加载简单地调用关系。你不需要join,你可以只拉关系。所以
在您的Customer 模型上,设置产品关系(您看起来拥有正确的多对多数据库结构):
public function products(){
return $this->belongsToMany("\App\Product");
}
然后在您的Controller 中,当您加载客户时,您可以同时抓取产品:
$customer = Customer::with("products")->first();
我只是以第一个客户为例 - 如果您愿意,您可以获取所有客户并循环使用客户和产品。
最后,当您想在刀片视图中调用数据时,您可以通过链接$customer模型来访问它。:
{{ $customer->products->first()->name }}
如果您想在刀片视图中循环浏览客户上的产品:
@foreach($customer->products as $product){}
而且,您仍然拥有 $customer 的主要数据:
$customer->name // Etc.
HTH
TA贡献1898条经验 获得超8个赞
如果要显示客户信息及其相关产品,则必须从表中选择数据。
在您的代码中,在控制器中,从您添加的所有表中获取所有数据:
->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;
在你的文件的开头(在命名空间区域或导入区域),所以它是这样的:
namespace App\Http\Controllers;
use DB;
use App\ //"your_file";
use Illuminate\Http\Request;
希望这有帮助:)
- 2 回答
- 0 关注
- 165 浏览
添加回答
举报