我尝试获取已记录的用户帖子count
的数量,以便向已登录的用户显示例如他们到目前为止发布了多少帖子或评论:
到目前为止我在author_id
表中的posts
列中将引用用户ID
这是我的Post
型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function author() {
return $this->belongsTo('App\User');
}
}
这是我的User
型号:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'role_id',
'email',
'password',
'name',
'avatar',
'remember_token',
'created_at',
'updated_at'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts()
{
return $this->hasMany('Post', 'author_id');
}
}
这是我的PostController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Auth;
use App\User;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('created_at', 'desc')->paginate(15);
$countTodayOrders = Post::whereRaw('Date(created_at) = CURDATE()')->count();
return view('theme.index', compact('posts', 'countTodayOrders'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function single($slug) {
$post = Post::where('slug', '=', $slug)->first();
$countTodayOrders = Post::whereRaw('Date(created_at) = CURDATE()')->count();
return view('theme.single', compact('post', 'countTodayOrders'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
}
任何人都知道我的错误是什么以及如何解决它?
答案 0 :(得分:0)
我明白了:)
我忽略了所有模型角色并直接使用了来自数据库的控制器插入数据,并将其与用户ID进行比较,如果它是真的(相同)将返回该数字。
如果您需要PostController
,请输入以下代码:
public function index()
{
$posts = Post::orderBy('created_at', 'desc')->paginate(15);
$countTodayOrders = Post::whereRaw('Date(created_at) = CURDATE()')->count();
$postscount = DB::table('posts')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('users')
->whereRaw('author_id = id');
})
->get();
return view('theme.index', compact('posts', 'countTodayOrders', 'postscount'));
}