我有数据透视表:
Schema::create('coach_user', function(Blueprint $table)
{
$table->integer('coach_id')->unsigned()->index();
$table->foreign('coach_id')->references('id')->on('coaches')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
如何通过Eloquent方法从此表中接收所有user_id?我是通过下一个方式完成的:DB::table('coach_user')->select('user_id')->distinct()->get()
但我收到了下一个结果:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[user_id] => 3
)
[1] => stdClass Object
(
[user_id] => 6
)
[2] => stdClass Object
(
[user_id] => 7
)
)
)
我需要收集user_ids,而不是stdClasses的集合。
答案 0 :(得分:2)
您应该使用以下关系:
User::has('coaches')->get()
此查询将为您提供至少拥有一个教练(在数据透视表中有user_id
)的所有用户。
如果尚未定义此关系,请定义它:
public function coaches()
{
return $this->belongsToMany(Coach::class);
}