我想显示为特定链接投票的用户列表,例如为链接1..etc投票的用户列表。我得到每个链接的投票数,但是我不知道如何获取用户。
链接模型:
/**
*
*links votes with respect to users
*@return
*/
public function votes(){
return $this->hasMany(Communitylinkvotes::class,'community_links_id');
}
// practise
public function userss(){
return $this->hasMany(Communitylinkvotes::class,'user_id','community_links_id');
}
CommunityLinkVotes模型或数据透视表模型
class Communitylinkvotes extends Model
{
//
protected $table = 'community_links_votes';
}
迁移选票
public function up()
{
Schema::create('community_links_votes', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->index();
$table->integer('community_links_id')->index();
$table->timestamps();
});
}
答案 0 :(得分:0)
您是否专门尝试从Link模型开始获取用户列表?
如果没有,请执行以下操作:
User::whereHas('votes', function($query) use ($some_id) {
$query->where('community_links_id', $some_id);
})->get();
如果是这样,我认为您在链接模型上的用户关系必须为hasManyThrough
。
像这样:
$this->hasManyThrough(User::class,Communitylinkvotes::class);
答案 1 :(得分:0)
我建议您使用belongsToMany关系。这将很容易得到您想要得到的。将关系添加到您的Communitylink
模型中。
public function users()
{
return $this->belongsToMany(User::class, 'community_links_votes','user_id', 'community_links_id');
//community_links_votes is the pivot table
}
控制器:
$link = Communitylink::find(1);
现在您可以像下面刀片中的示例一样获得该链接的用户:
@foreach($link->users as $user)
{{ $user->name }}
@endforeach
答案 2 :(得分:0)
与@emon相比,控制器和视图有了一些改进……让我知道它是否有效。
public function users()
{
return $this->belongsToMany(User::class,
'community_links_votes','user_id', 'community_links_id');
//community_links_votes is the pivot table
}
控制器:
$link = Communitylink::with('users') - >first();
And now you can get the users for that link like below
example in blade:
@foreach($link->users as $user)
{{ $user->first() - >name }}
@endforeach
答案 3 :(得分:-1)
public static function get_voted_users($id){
$result = DB::select(
DB::raw('SELECT users.name FROM users join community_links_votes on community_links_votes.user_id = users.id
join community_links on community_links.id = community_links_votes.community_links_id
where community_links.id = '.$id.' ')
);
return $result;
}