【问题标题】:How to make userEmail the foreignkey connect to the emailId in Tbluser model [closed]如何使用户通过电子邮件将外键连接到 Tbluser 模型中的电子邮件 ID [关闭]
【发布时间】:2020-07-16 06:57:47
【问题描述】:

我想连接来自Tblbooking 模型的userEmail 和来自Tbluser 模型的emailId

App\Models\Tbluser:

 protected $primarykey = 'EmailId';
 public function bookings(){
    return $this->hasMany('App\Models\Tblbooking');}

App\Models\Tblbooking:

protected $foreignkey='userEmail';
public function user(){
    return $this->belongsTo('\App\Models\Tbluser','userEmail','userEmail');
}

【问题讨论】:

  • 请输入格式化的问题,看起来不清楚您到底想要什么

标签: php laravel model foreign-keys relational-database


【解决方案1】:

App\Models\Tbluser - https://laravel.com/docs/7.x/eloquent-relationships#one-to-many

use App\Models\Tblbooking;

class Tbluser 
{
  public function bookings() 
  {
    return $this->hasMany(Tblbooking::class, 'userEmail', 'EmailId');
  }
}

App\Models\Tbluser - https://laravel.com/docs/7.x/eloquent-relationships#one-to-many-inverse

use App\Models\Tbluser;

class Tblbooking
{
  public function user() 
  {
    return $this->belongsTo(Tbluser::class, 'EmailId', 'userEmail');
  }
}

我建议重构您的代码并调用模型UserBooking。您可以使用protected $table 来定义模型应该使用的表,即protected $table = 'tbl_bookings';

use App\Models\User;

class Booking
{
  protected $table = 'tbl_bookings';

  public function user() 
  {
    return $this->belongsTo(User::class, 'EmailId', 'userEmail');
  }
}

另外,拥有一个单独的表格可能会有所帮助,您可以在其中存储所有电子邮件,以遵循 3NF (https://en.wikipedia.org/wiki/Third_normal_form#:~:text=Third%20normal%20form%20(3NF)%20is,in%201971%20by%20Edgar%20F.)。使用蛇形大小写命名列也是一种常见的做法。

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 2022-01-13
    • 2013-10-05
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多