2016-06-30 68 views
1

我有兩個CourseUser模型,它們之間存在ManyToMany關係。wherePivot laravel method and「in」operator

而且有一個名爲course_user透視表有這樣的額外列:

course_id 
user_id 
status 
score 

status柱舉行一個整數值,顯示在課程中註冊用戶的登陸狀態。

現在我想獲取特定用戶的所有課程,其中具有特定的course_id,並且其狀態包含至少一個數組值。

對於我寫了這個:

$user->courses() 
    ->where('course_user.course_id', $course->course_id) 
    ->wherePivot('status', 'not in', [1, 3, 10]) 
    ->count() 

但是,這並不工作,不會返回我的期望。

即使我試着從所示wherePivot方法不能正常工作,而忽略not in SQL操作上面的代碼生成的SQL。返回低於sql:

"select * from `courses` inner join `course_user` on `courses`.`course_id` = `course_user`.`course_id` where `course_user`.`user_id` = ? and `course_user`.`course_id` = ? and `course_user`.`status` != ? and `courses`.`deleted_at` is null" 

什麼是問題,我該如何解決這個問題?

回答

1

whereNotIn方法嘗試

類似的東西:

$user->courses() 
    ->where('course_user.course_id', $course->course_id) 
    ->whereNotIn('status', [1, 3, 10]) 
    ->count() 
1

使用戶模型的關係

公共職能課程(){$返回這 - >的hasMany( '課程', 'USER_ID');}

使在線使用者模式

public function users(){return $ this-> belongsTo('User','user_id');}

現在稱這種關係這樣

{{$用戶>課程() - > whereNotIn( '狀態',[1,3,10]) - >得到()} }

希望工程:)