簡體   English   中英

雄辯的ORM查詢關系

[英]Eloquent ORM querying relationship

假設我有兩個這樣的表:

users:
    - id
    - username

profiles:
    - user_id
    - name

使用datamapper ORM codeigniter,我可以編寫如下查詢:

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

它將返回配置文件名稱Diego的用戶。 我如何使用雄辯的ORM做到這一點? 我知道如何使用fluent(pure 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()->等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM