2016-11-05 191 views
1

這裏是我的代碼:Laravel 5.3關係

class Company extends Model { 
    public function employees() { 
     return $this->hasMany('Employee'); 
    } 
} 

class Employee extends Model{ 
    protected $table = "user_role_company"; 
    public function user(){ 
     return $this->belongsTo('User'); 
    } 
    public function company(){ 
     return $this->belongsTo('Company'); 
    } 
} 

class User extends Authenticatable { 
    public function employee(){ 
     return $this->hasMany('Employee'); 
    } 
} 

如果我運行:

$recordsTotal = User::with(['employee' => function ($query) use ($company_id) { 
    $query->where('company_id', $company_id); 
}])->count(); 

它返回所有的用戶數不僅empolyee計數。

我在做什麼錯?

感謝

回答

0

首先,你有一個「COMPANY_ID」,並在員工模型/ DB一個「user_ID的」列?

不管怎麼說,你可以試試這個查詢,而不是。

$recordsTotal = User::whereHas('employee', function ($q) use ($company_id) { 
    $q->where('company_id', $company_id); 
})->count(); 
+1

您的查詢工作!謝謝!! – user3844579

0

當創建關係需要引用整個命名空間或類似用戶::類的類

+0

命名空間被引用 – user3844579

0

當使用關係中,你可以在關係聲明莫代爾::類給出主鍵和地方兩個表的鍵引用正確的值,所以例如你可以有:

class Company extends Model { 
    public function employees() { 
     return $this->hasMany(Employee::class, 'company_id'); 
    } 
} 

這將引用的Employee表中的company_id列或你所設置的員工模態中曾經表。

您也可以通過foreign_key,local_key的關係,像這樣:

class Company extends Model { 
    public function employees() { 
    return $this->hasMany(Employee::class, 'foreign_key', 'local_key'); 
    } 
} 

一個類似的例子是:

class Company extends Model { 
    public function employees() { 
    return $this->hasMany(Employee::class, 'company_id', 'company_id'); 
    } 
} 

根據您的數據庫結構,你應該能夠只通過模態::類的關係,但它是很難給出一個完美的工作示例不知道你的確切數據庫結構,以及如何你有你的鑰匙/標識設置,意爲例子就是你的名爲id或COMPANY_ID主鍵。根據這個結構,你可以給這個鏡頭。

class Company extends Model { 
public function employees() { 
    return $this->hasMany(Employee::class); 
} 

}

還記得在陣列上返回集合時,要麼循環或簡單地使用$公司 - >員工() - > get()方法的另一種選擇是使用 - >第()而不是get()使用數組中的第一條記錄。

希望這會有所幫助,我決不是一個專家,還在學習laravel我自己,如果你有這種關係的任何進一步的問題或不能得到的代碼工作,我會盡量幫助我在哪裏可以。

也值得看一看這裏:Laravel Docs (Eloquent: Relationships)