class User extends AppModel { public $belongsTo = array( 'Group' => array( 'className' => 'Group', 'foreignKey' => 'group_id' ) ); } class Group extends AppModel { public $hasMany = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'group_id' ) ); }
$this->User->bindModel(array( 'belongsTo' => array( 'Group' => array( 'className' => 'Group', 'foreignKey' => 'group_id' ) ) )); $this->Group->bindModel(array( 'hasMany' => array( 'User' => array( 'className' => 'User', 'foreignKey' => 'group_id' ) ) ));
class User extends Eloquent { public function comments() { return $this->hasMany('Comment'); } } class Comment extends Eloquent { public function user() { return $this->belongsTo('User'); } }
$users = User::all(); foreach ($users as $user) { $user->bindModel(array( 'hasMany' => array( 'Comment' => array( 'foreignKey' => 'user_id' ) ) )); } $comments = Comment::all(); foreach ($comments as $comment) { $comment->bindModel(array( 'belongsTo' => array( 'User' => array( 'foreignKey' => 'user_id' ) ) )); }In this example, the bindModel() method is used inside loops to establish the relationships between the models. This code uses the Laravel package library.