Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 1 year ago.
0

Hello,
that is not difficult.
First create the proper DB Schema. There is no 'role_user_properties' table. The additional data of the relation is stored in the pivot table.

	public function up()
	{
		Schema::create('role_user', function(Blueprint $table)
		{
			$table->integer('role_id')
			->unsigned()
			->index();
			$table->integer('user_id')
			->unsigned()
			->index();
			$table->dateTime('expires');
			$table->integer('other_stuff');
			$table->timestamps();//only if needed
			$table->primary(array('role_id', 'user_id'));
		});
		Schema::table('role_user', function(Blueprint $table)
		{
			$table->foreign('role_id')
			->references('id')->on('roles')
			->onUpdate('cascade')
			->onDelete('cascade');
			$table->foreign('user_id')
			->references('id')->on('users')
			->onUpdate('cascade')
			->onDelete('cascade');
		});
	}
	public function down()
	{
		Schema::table('role_user', function(Blueprint $table){
			$table->dropForeign('role_user_role_id_foreign');
			$table->dropForeign('role_user_user_id_foreign');
		});
		Schema::drop('role_user');
	}

Inside your User model you will have a roles function to represent the relation.

public function roles(){
return $this->belongsToMany('Role', 'role_user')->withPivot('expires', 'other_stuff')->withTimestamps();
}

You CAN make the same, but reverse, in the Role model. But you don't have to. In that case you could "see" the raltionship from the User side, but not from the Role side. Declare relationships when you are sure you will use them.
Eager loading of pivot data is easy. Use the function name from your model.

$user = User::with('roles')->find($id);//eager loading
$expiredRoles = array();
foreach($user->roles as $role){//allready loaded
if(strtotime($role->pivot->expires) > time())
$expiredRoles[] = $role;
}

Actually, this relationship makes two joins to the users table. Use "pivot" to access the pivot data of the related model.
You can use where statements and other things...
If you found what you were searching for, please, mark this as solved and paste a link to stackoverflow as answer.

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

paengski13 paengski13 Joined 23 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.