douhu2131 2019-07-04 23:47
浏览 180

Laravel关系函数显示为null

I'm creating a small webshop where users can create orders and sellers can see the orders. I have defined relationships but the related functions are null. This is how my tables looks like in phpmyAdmin https://imgur.com/a/C2PSmFt

This is how I have defined relationships in my models.

User.php

public function sellerOrders()
{
    return $this->hasMany(Order::class);
}

Order.php

public function user()
{
    return $this->belongsTo('App\User', 'seller_id');
}

public function products()
{
    return $this->belongsToMany('App\Product')->withPivot('quantity','total','Subtotal');
}

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

 public function orderInfo()
 {
    return $this->belongsTo(OrderProduct::class, 'seller_id');
 }

This is my function in controller

$orders = Auth::user()->sellerOrders()->with('productInfo','orderInfo')->get();

When I dd($orders), this is what i get

 Collection {#305 ▼
 #items: array:1 [▼
 0 => Order {#286 ▼
  #table: "orders"
  #fillable: array:5 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:8 [▼
    "id" => 9
    "user_id" => 1
    "shipping_email" => "878888"
    "shipping_name" => "hattta"
    "shipping_city" => "kljjdjd"
    "shipped" => 0
    "created_at" => "2019-07-05 01:33:58"
    "updated_at" => "2019-07-05 01:33:58"
  ]
  #original: array:8 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:2 [▼
    "productInfo" => null
    "orderInfo" => null
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}
]
}

How can I show productInfo and orderInfo? Your help is really appreciated.

  • 写回答

2条回答 默认 最新

  • doukeyong3746487 2019-07-05 01:07
    关注

    Because You have in relation return hasMany => in orders you will have an array and since you queried it already, you have to query each item like so:

    foreach($orders as $order){
        echo $order->productInfo->propertyOfProductInforTable;
        echo $order->products->name; //or whatever is in your product table relation
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算