【发布时间】:2018-06-17 03:18:30
【问题描述】:
我正在 laravel 5.5 中开发一个多作者博客。我的情况是这样的: 每当一个人想以作者身份加入博客网站时,他/她必须发送申请表。这些申请将由一位编辑(在系统中的众多编辑中)批准/拒绝。 Users 表包含编辑器。
因此,无论何时制作应用程序,都可以由多个编辑人员查看。其中一位编辑需要预订申请以进行处理。这样做是为了防止多个编辑审查同一个申请。编辑预订申请后,他可以批准/拒绝作者申请。如果他在预订该应用程序后选择不处理该应用程序,他必须发布该应用程序以便其他编辑可以预订它。因此,一个应用程序不会同时映射到多个用户/编辑器。
现在我的要求是找到当前登录的编辑预订的所有应用程序。我无法形成正确的关系。
我的桌子是:
user (represent the editors)
Id, name, email, role_id, password
author_requests (represents the applications submitted by interested editors)
name, password, email, phone, city, country, profile_pic, bio, display_name, sample_article_link1, sample_article_link2, sample_article_link3, status
request_bookings (represent the bookings made by the editors)
id, item_id, item_type, user_id, status, status_date
在 request_bookings 表中,item_id 包含应用程序 ID,item_type 包含模型类型“auhor”。保留这些字段是因为与预订作者申请一样,需要对建议的帖子标题和帖子文章进行同样的操作。
我的模型是:
class User extends Authenticatable
public function bookings(){
return $this->hasMany("App\RequestBooking");
}
}
class AuthorRequest extends Model{
public function bookings(){
return $this->hasMany("App\RequestBooking");
}
}
class RequestBooking extends Model{
public function user(){
return $this->belongsTo("App\User");
}
public function authorReq(){
return $this->belongsTo("App\AuthorRequest");
}
}
当我尝试时: auth()->user()->bookings->authorReq
它给了我错误: 例外 此集合实例上不存在属性 [authorReq]。
如何获取已登录编辑器已预订的所有作者申请的列表?
【问题讨论】:
-
您在一系列预订上调用
->authorReq,您需要在单个模型上调用它。但即便如此,您的authorReq关系将无法正常工作,因为您似乎在request_bookings表上没有author_request_id。 -
非常感谢 devk。你让我继续前进。我通过更正关系解决了这个问题 public function authorReq(){ return $this->belongsTo("App\AuthorRequest", "item_id"); } 并在预订集合的每个实例上调用它
-
您也可以加载
authorReq,而不必在每个实例上调用该方法。RequestBooking::where('user_id', auth()->id())->with('authorReq')->get();
标签: php laravel eloquent relationship