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

时间:2018-01-24 15:16:33

标签: laravel laravel-5 eloquent laravel-5.4

我正在预约应用,用户可以在特定日期和时间与其他用户创建约会。我有一个用户表和约会表。每个约会都有一个发起者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('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->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

感谢您的任何建议。 亚历

1 个答案:

答案 0 :(得分:1)

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