samedi 28 novembre 2015

Laravel 5.1: Many-to-many alongside one-to-many relationship

I'm making an event RSVP app where a user creates an event (or events), and can allow other users to manage the event with them.

I also need to specify which user is the owner (creator) of an event.

My goal is to determine:

the user that owns an event

the users that can manage an event

the events a user owns

the events a user can manage

And also:

How I can create a user, then create an event, assign its owner and also add it to the event_user table at the same time

These are my current relationships...

Event Class - App\Event

public function owner()
{
    return $this->belongsTo('App\User', 'owner_id');
}

public function managers()
{
    return $this->belongsToMany('App\User');
}

User Class - App\User

public function owns()
{
    return $this->hasMany('App\Event', 'owner_id');
}

public function manages()
{
    return $this->belongsToMany('App\Event');
}

Current migrations...

Users migration - users

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

Events migration - events

$table->increments('id');

$table->integer('owner_id')->unsigned();

$table->string('name');

$table->timestamps();

$table->foreign('owner_id')->references('id')->on('users')
    ->onUpdate('cascade')->onDelete('cascade');

Event User - event_user

$table->increments('id');
$table->integer('event_id')->unsigned();
$table->integer('user_id')->unsigned();

$table->foreign('event_id')->references('id')->on('events')
      ->onUpdate('cascade')->onDelete('cascade');

$table->foreign('user_id')->references('id')->on('users')
      ->onUpdate('cascade')->onDelete('cascade');

However when I play around in artisan tinker I can only get one of the methods to work.

$user = App\User::find(1);
$event = new App\Event(['name' => 'Event 1']);

$user->owns()->save($event);

The above example works to assign the owner_id in the events table

$user = App\User::find(1);
$event = new App\Event(['name' => 'Event 2']);

$user->sites()->save($site);

This fails outright, where previously it did work before adding the one-to-many methods...

How can I create a user, then create an event, assign its owner and also add it to the event_user table?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire