2017-05-01 235 views
0

我試圖讓登錄的用戶的帖子數量count所以它顯示了登錄的用戶,例如他們有多少的信息或評論至今出版:的hasMany雄辯關係5.4

我至今是author_id列在posts表將參考用戶ID

posts table image

這是我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

順便說一句你在'$ countTodayOrder'會得到些什麼? – imrealashu

+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')); 
    }