简体   繁体   English

无法在雄辩的laravel 5.1中建立hasMany关系

[英]not able to make hasMany relationship in eloquent laravel 5.1

Hi I am new to laravel and trying to make one to many relationship where I am trying to get customer name from customers and order_no against the customer name from orders table, here is code 嗨,我是laravel的新手,并尝试建立一对多关系,在这里我试图从客户那里获取客户名称,而从订单表中获取客户名称与order_no,这是代码

//--customer Model
class customer extends Model {
  public function order(){
    return $this->hasMany('App\order');
 }
}

//-- order Model
class order extends Model {
    public function customer(){
    return $this->belongsTo('App\customer');
       }
     }

  //--controller
  public function searchRecord(){
  $customer = customer::all();
  return view('orders.searchRecord')->with('customer', $customer);
  }

  //--View

 @foreach($customer as $customer)                                        
 {{$customer->customer_name}}<br />
 @endforeach

when I use {{$customer->customer_name}} it prints all customer name fine, but when I use {{$customer->order}} it prints the whole json of order table, but if I {{$customer->order->order_no}} it gives error undefined property $order_no. 当我使用{{$customer->customer_name}}它会很好地打印所有客户名称,但是当我使用{{$customer->order}}它会打印订单表的整个json,但是如果我{{$customer->order->order_no}}它给出错误的未定义属性$ order_no。

You have defined your customer->order relation as one-to-many , which means that a single customer can have multiple orders . 您已将客户与订单的关系定义为一对多 ,这意味着单个客户可以拥有多个订单 Therefore, when you access $customer->order you are accessing a Collection object that stores all customer's order, not a single order. 因此,当您访问$ customer-> order时,您将访问一个Collection对象,该对象存储所有客户的订单,而不是单个订单。 There is no order_no property in Collection class, that's why you're getting the error. Collection类中没有order_no属性,这就是您收到错误的原因。

One way to access invidual orders you'll need to iterate through the collection: 您需要遍历集合的一种访问单个订单的方法:

foreach ($customer->order as $order) {
  echo $order->order_no;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM