繁体   English   中英

Laravel:关系并非在请求的所有方面都起作用

[英]Laravel : relations are not working in every ways of the request

给定两个表:

Package
--------
int id
int parcel_id
int order_id
timestamps()

Order
--------
int id
int user_id
int search_id
timestamp shipping_date
timestamps()

有一个或多个Package对象属于Order

一个Order对象分别具有一个或多个Package对象。

包装型号:

public function order() {
    return $this->belongsTo('App\Order');
}
public function parcel() {
    return $this->belongsTo('App\Parcel');
}

订购型号:

public function search() {
    $this->belongsTo('App\Search');
}
public function user() {
    $this->belongsTo('App\User');
}
public function packages() {
    $this->hasMany('App\Package');
}

题 :

我成功获得了PackageOrder ,但无法获得与Order相关联的Packages 这是为什么 ?

我确实有相同的行为,这一次是从User那里,找到所属的Search。

当我尝试找到“搜索”->“用户”时,搜索工作正常。

我与User has_many Adresses具有完全相同的Model结构,并且Address属于User ,在两种方式下均能很好地工作。

我的猜测是这是因为两个表都涉及许多键,但是我仍然将列名指定为belongToTo / hasMany属性, 如果我没记错的话,雄辩的关系是基于列和表名,而不是基于“真实”关系MySQL关系(外键等)。

PHP工匠修补匠中的插图:

>>> $package = App\Package::where('id', 224)->first()
=> App\Package {#800
     id: 224,
     parcel_id: 2,
     weight: 10,
     created_at: "2016-12-29 14:00:58",
     updated_at: "2016-12-29 14:00:58",
     order_id: 115,
   }
>>> $package->order
=> App\Order {#743
     id: 115,
     user_id: 1,
     search_id: 1,
     created_at: "2016-12-29 14:00:58",
     updated_at: "2016-12-29 14:00:58",
     shipping_date: "2016-12-29 14:00:58",
   }
>>> $order = App\Order::where('id', 115)->first()
=> App\Order {#804
     id: 115,
     user_id: 1,
     search_id: 1,
     created_at: "2016-12-29 14:00:58",
     updated_at: "2016-12-29 14:00:58",
     shipping_date: "2016-12-29 14:00:58",
   }
>>> $order->packages
LogicException with message 'Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation'
>>> $order->packages()
=> null

您在订单模型上缺少退货声明。

public function search() {
    return $this->belongsTo('App\Search');
}
public function user() {
    return $this->belongsTo('App\User');
}
public function packages() {
    return $this->hasMany('App\Package');
}

您正在返回void这不是一个laravel关系。 ;)

暂无
暂无

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

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