【问题标题】:Laravel 5.3 belongsToMany return null, pivot dataLaravel 5.3 belongsToMany 返回空值,透视数据
【发布时间】:2017-06-04 06:30:03
【问题描述】:

我有下一个型号:

class Product extends Model{
    protected $table = 'products';

    public function payments()
    {
        return $this->belongsToMany('App\Payment', 'payment_product', 'product_id', 'payment_id')
    }
}

class Payment extends Model{
    protected $table = 'payments';

    public function products(){
        return $this->belongsToMany('App\Product');
    }
}

数据透视表:payment_product(id, product_id, payment_id)

口才

 public function details($id){
        $product = Product::with('payments')->find($id);
        dd($product->payments); // return null
        return view('products.details', ['product' => $product]);
    }

我需要引入一个 foreach,但 $product->payments 为空。这是为什么 ? 所有的表都不是空的。

UPD 子查询 $this->belongsToMany('App\Payment', 'payment_product', 'product_id', 'payment_id'); 结果:

【问题讨论】:

  • 仅供参考,因为您遵循 laravel 的命名约定,您不必在关系中提供表名/列。

标签: laravel orm eloquent laravel-5.3


【解决方案1】:

尝试:

public function payments()
{
    return $this->belongsToMany('App\Payment', 'payment_product', 'payment_id', 'product_id')
}

我认为你的 FK 顺序错误。

事实上,我认为您不需要指定任何其他内容:

public function payments()
{
    return $this->belongsToMany('App\Payment')
}

【讨论】:

  • 我试过了,public function payment(){ return $this->belongsToMany('App\Payment'); } 不工作
【解决方案2】:

看起来您正在根据不相关的字段连接两个表。

当你这样做时

return $this->belongsToMany('App\Payment', 'payment_product', 'product_id', 'payment_id')

您的表productspayment_product 内部连接
products.product_id = payment_product.payment_id。 但我认为这两列不是相关的键。相反,在您的 payment_product 中,使用 products.product_id 加入此表中的 product_id。 那可能行得通。

【讨论】:

  • 模型支付和产品已保护 $primaryKey = 'id'; $product = Product::with('payments')->find($id); dd($product->relationsToArray();); array:1 [▼ "payments" => array:2 [▼ 0 => array:7 [▶] 1 => array:7 [▶] ] ] 很好。但是 foreach($product->payment as $payment){...}, 错误:为 foreach 提供的参数无效
  • 查询没有返回任何结果。在 mysql 终端中运行相同的原始 sql 命令,看看是否在那里得到结果。如果没有,您可能加入错误。
【解决方案3】:

将付款重命名为 payment_method:

public function payments_method(){
   return $this->belongsToMany('App\Payment'); //or ('App\Payment', 'payment_product', 'payment_id', 'product_id') 
}

 $product = Product::find($id);
 $product->payments_method; //this is work

这太神奇了:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2018-09-26
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多