【问题标题】:Unable to define relations correctly in laravel 5.5 application无法在 laravel 5.5 应用程序中正确定义关系
【发布时间】: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


【解决方案1】:

默认情况下,laravel 使用方法名称后缀为_id 的列,它会根据您的方法名称查找authorReq_id。因此,您可以在author_requests 表上创建一个列,如果您没有任何定义关系的列。或者,如果您已经有一个列但名称不同,那么您可以将第二个参数传递给belongsTo 方法,如下所示:

public function authorReq()
{ 
     return $this->belongsTo("App\AuthorRequest", 'column_that_references_foreign_key'); 
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多