我想在laravel 5.2 app中实现基于用户的侧边栏,其中包含大多数帖子和评论, 我想向前5位用户展示最多帖子和评论。 例如: 用户名:“Mohcin”,帖子:30,回答:20 提前致谢
答案 0 :(得分:0)
步骤:
app/Providers/AppServiceProvider.php
boot
方法。像这样:
//Assuming you want to pass the var to the view: sidebar.blade.php inside resources/views/layout
view()->composer('layout.sidebar', function($view){
$topUsers = User::topUsers(); //Create a query or scope to do this...
//After populate topUsers, you have to pass it to the view using:
$view->with('topUsers', $topUsers);
});
在您的视图中:`resources / views / layout / sidebar.blade.php,您可以使用这样的简单$ topUsers访问用户:
foreach($topUsers as $user) {
var_dump($user);
}
答案 1 :(得分:0)
用户模型:
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function questions(){
return $this->hasMany('\App\Question');
}
public function answers(){
return $this->hasMany('\App\Answer');
}
问题模型:(发布模型)
public function User(){
return $this->belongsTo('\App\User');
}
public function answers(){
return $this->hasMany('\App\Answer');
}
public static function your_questions(){
return static::where ('user_id','=',Auth::user()->id)->paginate(50);
}
public static function unsolved(){
return static::where ('solved','=',0)->orderby('id','DESC')->latest()->paginate(50);
}
public static function unsolvedbar(){
return static::where ('solved','=',0)->orderby('id','DESC')->latest()->take(3)->get();;
}
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}