2013-10-04 131 views
2

比方說,我有兩個表是這樣的:雄辯ORM查詢關係

users: 
    - id 
    - username 

profiles: 
    - user_id 
    - name 

使用DataMapper的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(); 

回答

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並可以鏈接,例如,在哪裏() - >哪裏() - > orderBy() - >等....

+2

與你的答案我寫了這個查詢: User :: with('profile') - > where('name', '); - > get(); 但是它返回了這個錯誤: SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'name'(SQL:select * from users where name = ?)(Bindings:array(0 =>'Diego',)) –

+0

這裏的所有查詢都將在用戶表上運行,而不是配置文件關係,這不是OP需要的。 –