Eloquent :: Один к одному, где активен в обеих таблицах, но в определенных ролях

Я пытаюсь вернуть только определенные профили для пользователей, у которых есть роли (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 в таблице профилей, их не будет. Мне нужно, чтобы они не показывали, установлены ли в таблице «Пользователь» или «Профиль» эти строки как неактивные. Потому что у вас может быть пользователь, но ему может не понадобиться активный профиль.


person Dan Kinchen    schedule 08.09.2016    source источник


Ответы (1)


Хорошо, я понял!

$data['experts'] = User::whereIn('role_id', array(5, 6))
        ->where('is_active', '1')
        ->whereHas('profile', function($q){
            $q->where('is_active', '1');
        })
        ->with('profile')
        ->orderBy('first_name', 'ASC')
        ->get();

Если вы хотите знать, как вернуть это в twig....

{% if experts|length > 0 %}
    <ul>
    {% for item in experts %}
        <li>First Name: {{ item.first_name }}, Bio: {{ item.profile.bio }}, Avatar: {{ item.profile.avatar }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No records found.</p>
{% endif %}
person Dan Kinchen    schedule 08.09.2016