【问题标题】:LARAVEL ELOQUENT - I want to add column from user table to a relation tableLARAVEL ELOQUENT - 我想将用户表中的列添加到关系表中
【发布时间】:2018-04-17 16:33:03
【问题描述】:

我对 laravel 中的 eloquent orm 不太熟悉

我有 3 张桌子

 -- leads
       |
        Lead_appointments

   and users table

因为lead_appointments属于lead_id的leads引用id

leads_appointments 有一个名为 created_by 的列,其中包含用户 ID

当使用 eloquent 查询时,我正在尝试查询用户名和电子邮件以及结果作为另一列

首席模特

  class Leads extends Model
     { 
        public function appointments()
        {
           return $this->hasMany('App\Models\LeadsAppointments', 'lead_id');
        }
     }

我在控制器中的雄辩查询

   return $this->lead->with('appointments')->find($id);

结果是这样的

在约会中,我还想要用户电子邮件和姓名以及由其中创建的人

但我想不通

【问题讨论】:

  • "leads_appointments 有一个名为 created_by 的列,其中包含用户 ID",所以你有用户模型好吗?用户和约会之间有什么关系吗?
  • 不需要关系,实际上我想添加用户的电子邮件和姓名和ID而不是created_by列作为列@ChiragPatel

标签: php mysql laravel-5 eloquent


【解决方案1】:

像这样向LeadAppointment模型添加关系:

class LeadAppointment extends Model
{ 
  public function users()
  {
    return $this->belongsTo('App\Models\User', 'created_by');
  }
}

并像这样改变潜在客户模型:

 class Leads extends Model
     { 
        public function appointments()
        {
           return $this->hasMany('App\Models\LeadsAppointments', 'lead_id')->with('users');
        }
     }

【讨论】:

  • 您可以通过lead->user->email和类似方式访问列。
  • 用户 ID 为空,
  • 我需要一个结果|created-by|email|name| . @SakiburRahuman
  • 运行查询后的结果是什么?
  • 我已经编辑了我的答案。检查它现在是否正常工作。
猜你喜欢
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 2014-06-25
  • 2015-01-01
  • 2021-05-09
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多