Created
May 9, 2014 15:03
-
-
Save lighta971/f2c8e9be27df2ceb5569 to your computer and use it in GitHub Desktop.
Laravel Custom Pivot Model definition example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//https://github.com/laravel/framework/issues/2093#issuecomment-39154456 | |
use Illuminate\Database\Eloquent\Model as Eloquent; | |
use Illuminate\Database\Eloquent\Relations\Pivot; | |
class User extends Eloquent { | |
public function groups() { | |
return $this->belongsToMany('Group'); | |
} | |
public function newPivot(Eloquent $parent, array $attributes, $table, $exists) { | |
if ($parent instanceof Group) { | |
return new UserGroup($parent, $attributes, $table, $exists); | |
} | |
return parent::newPivot($parent, $attributes, $table, $exists); | |
} | |
} | |
class Group extends Eloquent { | |
public function users() { | |
return $this->belongsToMany('User'); | |
} | |
public function newPivot(Eloquent $parent, array $attributes, $table, $exists) { | |
if ($parent instanceof User) { | |
return new UserGroup($parent, $attributes, $table, $exists); | |
} | |
return parent::newPivot($parent, $attributes, $table, $exists); | |
} | |
} | |
class UserGroup extends Pivot { | |
public function user() { | |
return $this->belongsTo('User'); | |
} | |
public function group() { | |
return $this->belongsTo('Group'); | |
} | |
// Note: Adding relationships to a pivot model means | |
// you'll probably want a primary key on the pivot table. | |
public function posts($value) { | |
return $this->hasMany('Post'); // example relationship on a pivot model | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice bro