为了账号安全,请及时绑定邮箱和手机立即绑定

如何从laravel 5中的两个相关表中获取数据

如何从laravel 5中的两个相关表中获取数据

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'; }我的代码有什么问题,因为我得到了错误的结果。我想展示客户信息及其相关产品。
查看完整描述

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


查看完整回答
反对 回复 2021-11-26
?
汪汪一只猫

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;

希望这有帮助:)


查看完整回答
反对 回复 2021-11-26
  • 2 回答
  • 0 关注
  • 146 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信