【问题标题】:How to join a table that has been joined by another table如何加入已被另一个表加入的表
【发布时间】:2020-04-15 07:38:15
【问题描述】:

我有 3 个表格(产品、产品详细信息、贷款报告)。

我想在贷款报告表中显示产品类别。产品表和产品明细表是一对多的关系,产品明细表和贷款报表表是一对多的关系。

产品

id
product_categories

产品详情

id
product_name

贷款报告

id
date
amount

我已经用这段代码展示了它,

$data = DB::table('loan_reports')
            ->join('product_details', 'loan_reports.product_details_id', '=', 'product_details.id')
            ->join('products', 'product_details.products_id', '=', 'products.id')
            ->get();

我想用 Eloquent orm 来做,但总是出错。 请帮帮我!

我要显示的栏目大致是这样的

| date | product_categories | product_name | amount |

我得到的错误如下:

试图获取非对象的属性“product_name”

【问题讨论】:

  • 错误是什么?
  • 可以显示错误信息吗?
  • @timbiegeleisen 它说“试图获取非对象的属性 'product_name'”

标签: php mysql laravel


【解决方案1】:

您可能想查看“有很多通过”的关系:

https://laravel.com/docs/5.8/eloquent-relationships#has-many-through

【讨论】:

    【解决方案2】:

    在 ProductDetails 模型中,创建关系。

     public function product_info()
     {
       return  $this->belongsTo('App\Models\Product','id','products_id');
     }
     public function loan_reports()
     {
       return  $this->hasOne('App\Models\LoanReports','product_details_id','id');
     }
    

    使用检索结果

     $product_details = ProductDetails::get(); 
     foreach($product_details as $product_details)
     {
       echo $product_details->product_categories;
       if(isset($product_details->product_info))
       {
         echo $product_details->product_info->product_name;
       }
       if(isset($product_details->loan_reports))
       {
         echo $product_details->loan_reports->date;
         echo $product_details->loan_reports->amount;
       }
     }
    

    【讨论】:

    • 对不起,hasOne 和 belongsTo 有什么区别?因为我在我的代码中使用了 belongsTo
    • belongsTo其实是hasOne的反面。但目的是一样的。简单的例子是filia_fixi hasOne phone,phone belongsTo filia_fixi。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多