Я пытаюсь вернуть только определенные профили для пользователей, у которых есть роли (role_id 5 и 6), которые активны в обеих таблицах. Также было бы неплохо, если бы я мог также заказывать по first_name ASC (таблица пользователей).
user
+---------+---------+-------------+-----------+
| user_id | role_id | first_name | is_active |
+---------+---------+-------------+-----------+
| 1 | 5 | Dan | 1 |
| 2 | 6 | Bob | 0 |
+---------+---------+-------------+-----------+
profile
+------------+---------+------+-------------+-----------+
| profile_id | user_id | bio | avatar | is_active |
+------------+---------+------+-------------+-----------+
| 1 | 1 | text | example.jpg | 1 |
| 2 | 2 | text | noimage.gif | 1 |
+------------+---------+------+-------------+-----------+
Моя пользовательская модель
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class User extends Model{
protected $table = 'user';
protected $primaryKey = 'user_id';
protected $fillable = [
'role_id',
'first_name',
'is_active'
];
public function scopeActive(){
return $this->where('is_active', '=', 1);
}
public function role(){
return $this->belongsTo('App\Model\Role');
}
public function profile(){
return $this->hasOne('App\Model\Profile');
}
}
Моя профильная модель
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model{
protected $table = 'profile';
protected $primaryKey = 'profile_id';
protected $fillable = [
'user_id',
'avatar',
'is_active'
];
public function scopeActive(){
return $this->where('is_active', '=', 1);
}
public function user(){
return $this->belongsTo('App\Model\User');
}
}
Мой пользовательский контроллер
namespace App\Controller\User;
use App\Model\User;
use App\Model\Profile;
use App\Controller\Controller;
final class UserController extends Controller{
public function listExpert($request, $response){
$user = User::active()->whereIn('role_id', array(5, 6))->orderBy('first_name', 'asc')->get();
$profile = $user->profile ?: new Profile;
$data['experts'] = $profile->active()->get();
$this->view->render($response, '/Frontend/experts.twig', $data);
return $response;
}
}
Так что у меня все записи в порядке. Я получаю все профили, но не те, которые принадлежат только role_id 5 и 6 в пользовательской таблице. Также, если я установлю для is_active значение 0 в пользовательской таблице, они все равно будут отображаться. Но если я установлю is_active в таблице профилей, их не будет. Мне нужно, чтобы они не показывали, установлены ли в таблице «Пользователь» или «Профиль» эти строки как неактивные. Потому что у вас может быть пользователь, но ему может не понадобиться активный профиль.