【问题标题】:Laravel hasManyThrough polymorphic table not workingLaravel hasManyThrough 多态表不起作用
【发布时间】:2020-05-09 06:08:13
【问题描述】:

我有以下关系:

class Project extends Model
{
   public function invitors()
   {
      return $this->hasMany(Invitation::class)
   }
}

// User model
class User extends Model
{
    public function invitations()
    {
        return $this->morphMany('App\Invitation', 'invitee');
    }
}

// Business Model
class Business extends Model
{
    public function invitations()
    {
        return $this->morphMany('App\Invitation', 'invitee');
    }
}

// Invitation model
class Invitation extends Model
{
    public function invitee()
    {
        return $this->morphTo();
    }

    public function project()
    {
       return $this->belongsTo(Project::class);
    }
}

我想要的是获得项目邀请者(用户和企业)。当我从$project->invitors->invitee 使用时,它不起作用。

【问题讨论】:

  • $project->find(1)->invitors 应该可以正常工作
  • 我有项目详情,已经绑定到路由了。

标签: php mysql laravel eloquent polymorphism


【解决方案1】:

在您的示例中,$project->invitorsInvitation 实例的集合,并且它没有属性 invitee。您可以使用助手pluck 循环$project->invitors 并获取他们的受邀者:

$invitees = $project->invitors->pluck('invitee');

作为对第一条评论的回应: 要获取获取的链接模型(“受邀者”)的特定属性,您可以指定访问器:

class Business extends Model
{
    ...

    public function getInviteeNameAttribute() {
        return $this->name;
    }
}

class User extends Model
{
    ...

    public function getInviteeNameAttribute() {
        return $this->first_name . ' ' . $this->last_name;
    }
}

...然后从invitee获取该属性:

$invitees[0]->invitee_name

https://laravel.com/docs/7.x/eloquent-mutators#defining-an-accessor

【讨论】:

  • 我们如何将 select 子句添加到 pluck 中,我应该从受邀者 businessuser 中选择特定列,并为这些列设置别名,假设我应该从业务中获取它的名称,但从用户我应该得到名字和姓氏的连接作为名字
猜你喜欢
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 2014-05-12
  • 2015-03-04
  • 2018-09-25
  • 1970-01-01
  • 2015-12-14
相关资源
最近更新 更多