在Laravel中,如何在同一条记录上同时设置多个hasMany(1对多)关系?

In Laravel, how to set multiple hasMany (1 to many) relationships on the same record simultaneously?

我正在制作一个约会应用程序,一个用户可以在特定的日期和时间创建与另一个用户的约会。我有一个用户 table 和一个约会 table。每个约会都有一个发起者 ID(建议约会的用户)和一个接收者 ID(收到约会请求的用户),并且模型有 hasMany 关系(代码如下)

我的问题是,当我创建约会时,如何Eloquent 将发起者和接受者与新约会相关联。查看文档中的语法,我可以轻松地做例如只是发起者,像这样:

$initiator = User::find(Auth::user()->id); // Get user from DB who is the initiator
$appt = $initiator->appts_initiator()->create(['address' => $request->input('address'), 'whendatetime' => $request->input('whendatetime')]);

或者我可以只做收件人:

$recipient = User::where('email', $request->input('email'))->first(); // Get recipient user
$appt = $recipient->appts_recipient()->create(['address' => $request->input('address'), 'whendatetime' => $request->input('whendatetime')]);

在其中包含 create() 的那一行中,我需要获取 Eloquent 以关联发起者和接收者。或者我是否必须手动注入正确的 ID 作为 create() 中的参数之一,这似乎绕过了 Eloquent!

的要点

相关型号编码:

class User extends Authenticatable
{
    protected $fillable = ['name', 'email', 'password'];

    // Get all of the user's appointments where they are an initiator:
    public function appts_initiator()
        {
            return $this->hasMany('App\Appointment', 'initiator_id');
        }

    // Get all of the user's appointments where they are a recipient:
    public function appts_recipient()
        {
            return $this->hasMany('App\Appointment', 'recipient_id');
        }
}

class Appointment extends Model
{
    protected $fillable = array('whendatetime', 'address', 'minuteslate');

    // Get user who is the initiator for this appointment:
    public function initiator_user()
        {
            return $this->belongsTo('App\User', 'initiator_id');
        }

    // Get user who is the recipient for this appointment:
    public function recipient_user()
        {
         return $this->belongsTo('App\User', 'recipient_id');
        }

    // Get the payment for this appointment:
    public function get_payment()
        {
            return $this->hasOne('App\Payment'); // Default foreign key (appointment_id)
        }
}

用户table的相关位:

$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');

和约会table:

$table->increments('id');
$table->integer('initiator_id')->unsigned(); // User who initiated to appointment
$table->integer('recipient_id')->unsigned(); // User who receives the appointment request
$table->dateTime('whendatetime'); // Date and time of appointment
$table->string('address'); // Address of the appointment

感谢您的任何建议。 亚历克斯

$initiator = Auth::user();
$recipient = User::where('email', $request->input('email'))->first();
$appt = new Appointment();
$appt->address = $request->input('address'); 
$appt->whendatetime = $request->input('whendatetime');
$appt->initiator_user()->associate($initiator);
$appt->recipient_user()->associate($recipient);
$appt->save();