假设我有两个这样的表:
users:
- id
- username
profiles:
- user_id
- name
使用datamapper ORM codeigniter我可以写一个这样的查询:
$users = new User();
$users->where_related('profile', 'name', 'Diego');
$users->get();
它将返回配置文件名为Diego的用户。如何使用Eloquent ORM实现这一目标?我知道如何使用流利的(纯sql)做这个,但不知道如何使用雄辩的方式做到这一点。
编辑:我使用此查询解决了这个问题,但感觉很脏,有更好的方法吗?
$users = Users::join('profiles', 'profiles.user_id', '=', 'user.id')->where('profiles.name', 'Diego')->get();
答案 0 :(得分:0)
您必须为每个表创建模型,然后指定关系。
<?php
class User {
protected $primaryKey = 'id';
protected $table = 'users';
public function profile()
{
return $this->hasOne('Profile');
}
}
class Profile {
protected $primaryKey = 'user_id';
protected $table = 'profiles';
}
$user = User::where('username', 'Diego')->get();
// Or eager load...
$user = User::with('Profile')->where('username', 'Diego')->get();
?>
Laravel文档使这个过程非常清晰:http://four.laravel.com/docs/eloquent#relationships。
请注意,Fluent方法可用于Eloquent并且可以链接,例如其中,() - 化合物其中() - &GT; ORDERBY() - &GT;等等...