【问题标题】:How to get data from two related tables in laravel 5如何从 laravel 5 中的两个相关表中获取数据
【发布时间】:2019-08-17 20:42:02
【问题描述】:

我有 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'; }

我的代码有什么问题,因为我得到了错误的结果。我想展示客户信息及其相关产品。

【问题讨论】:

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

这就是 Laravel 让生活变得轻松的地方。通过在模型上添加关系,您可以通过预先加载简单地调用关系。你不需要join,你可以拉关系。所以

在您的客户模型上,设置产品关系(您看起来拥有适合多对多的数据库结构):

 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

【讨论】:

    【解决方案2】:

    如果您想显示客户信息及其相关产品,您必须从表格中选择数据。

    在您的代码中,在控制器中,从所有表中获取所有数据 你添加:

    ->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;
    

    希望这有帮助:)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 2019-02-20
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    相关资源
    最近更新 更多