両方のテーブルでアクティブなロール (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;
}
}
だから私はすべての記録をうまく取得しています。すべてのプロファイルを取得していますが、user テーブルの role_id の 5 & 6 のみに属するプロファイルは取得していません。また、ユーザー テーブルで is_active を 0 に設定しても、表示されます。しかし、プロファイル テーブルに is_active を設定すると、そうではありません。User テーブルまたは Profile テーブルでこれらの行が非アクティブに設定されているかどうかを表示しないようにする必要があります。ユーザーを持つことはできますが、アクティブなプロファイルを望んでいない可能性があるためです。