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



我正在制作一个约会应用程序,用户可以在特定日期和时间与其他用户创建约会。我有一个用户表和一个约会表。每个约会都有一个发起人 ID(建议约会的用户)和一个收件人 ID(接收约会请求的用户),并且模型具有许多关系(下面的代码)

我的问题是,当我创建约会时,如何让 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('AppAppointment', 'initiator_id');
}
// Get all of the user's appointments where they are a recipient:
public function appts_recipient()
{
return $this->hasMany('AppAppointment', '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('AppUser', 'initiator_id');
}
// Get user who is the recipient for this appointment:
public function recipient_user()
{
return $this->belongsTo('AppUser', 'recipient_id');
}
// Get the payment for this appointment:
public function get_payment()
{
return $this->hasOne('AppPayment'); // Default foreign key (appointment_id)
}
}

用户表的相关位:

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

和预约表:

$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();

最新更新