class User extends Eloquent { public function passport() { return $this->has_one('Passport');//描述了在每一个用户都有对应的passport } }
再来看看我们的Passport类(用于操作passport表)中,有一个外键user_id$user = User::find(1);//实例化User表 if(is_null($user)) { echo "No User found!"; return; } if($user->passport) { //$user->passport将会得到$user对应的Passport实例,再来获取number echo "The user's passport number is".$user->passport->number; }
class Passport extends Eloquent { public function user() { return $this->belongs_to('User');//这样我们就表达出了user_id这个外键对应的是user表 } }
$passport = Passport::find(1); echo $passport->user->name;
表playersclass Team extends Eloquent { public function palyers() { return $this->has_many(‘Player’); } }
接着咱们来看看改如何来得到一个小组的所有成员呢?class Player extends Eloquent { public function team() { return $this->belongs_to('Team'); } }
$team = Team::find(1); $palyers = $team->palyers()->get(); foreach($players as $player) { echo '$play->name is on team $team->name'; }
Course表的模型class Student extends Eloquent { public function courses() { return $this->has_many_and_belongs_to('Course'); } }
class Course extends Eloquent { public function students() { return $this->has_many_and_belongs_to('Student'); } }
让我们来使用我们的模型,通过找到id为1的学生选修的课程
$student = Student::find(1); if(is_null($student)) { echo "没有此学生"; exit; } if(!$student->courses) { echo "学生: $student->name 没有选修任何课程。"; exit; } else { foreach($student->courses as $course) { echo "学生:$student->name 选修的课程有:$course->name"; } }
$course = Course::find(1); if(is_null($course)) { echo "没有此课程"; exit; } if($course->students) { foreach($course->students as $student) { echo "该课程:$course->name选修的学生有:$student->name"; } } else { echo "课程暂时没有学生选修!"; exit; }
$course = Course::find(12); if(is_null($course)) { echo "该课程不存在!" exit; } $new_student = array( 'name' => '沖田杏梨'; ); $course->students()->insert($new_student);