雄辩的 ORM 查询关系


Eloquent ORM querying relationship

假设我有两个这样的表:

users:
    - id
    - username
profiles:
    - user_id
    - name

使用数据映射器 ORM 编码器,我可以编写这样的查询:

$users = new User();
$users->where_related('profile', 'name', 'Diego');
$users->get();

它将返回配置文件名称为Diego的用户。我如何使用雄辩的ORM实现这一目标?我知道如何使用流利(纯sql)来做到这一点,但不知道如何使用雄辩来做到这一点。

编辑:我使用此查询解决了这个问题,但感觉很脏,有没有更好的方法可以做到这一点?

$users = Users::join('profiles', 'profiles.user_id', '=', 'user.id')->where('profiles.name', 'Diego')->get();

必须为每个表创建模型,然后指定关系。

<?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 并且可以链接,例如 where()->where()->orderBy()->etc....