2016-08-15 155 views
0

我稱之爲列辣味帖子表,我試圖用elequent ORM save()方法Laravel 5.2 Elequent ORM保存()不工作

這是爲了更新我的代碼:

$rank = new Ranking; 
$post = Post::where('id', $post_id) 
    ->select(DB::raw("(select count(*) from votes where votes.vote = '1' and votes.post_id = posts.id) as upvotes, (select count(*) from votes where votes.vote = '0' and votes.post_id = posts.id) as downvotes, posts.created_at, posts.hotness")) 
    ->first(); 

echo "Starting HOTNESS: " . $post->hotness; //CORRECT VALUE 

$post->hotness = $rank->hotness($post->upvotes, $post->downvotes, strtotime($post->created_at)); 

echo "Updated HOTNESS: " . $post->hotness; //CORRECT VALUE 

$post->save(); 

當我運行此命令並檢查我的數據庫後,後熱度仍然在起始值。兩個回顯都會打印出正確的值,並且不會出現錯誤。任何想法爲什麼它沒有更新?

回答

0

我想通了。事實證明,你不能在你正在更新的模型上使用'select',所以我改變了我的代碼,並且它工作。

$rank = new Ranking; 
$postVotes = Post::where('id', $post_id) 
    ->select(DB::raw("(select count(*) from votes where votes.vote = '1' and votes.post_id = posts.id) as upvotes, (select count(*) from votes where votes.vote = '0' and votes.post_id = posts.id) as downvotes")) 
    ->first(); 

$upvotes = $postVotes->upvotes; 
$downvotes = $postVotes->downvotes; 

$post = Post::where('id', $post_id)->first(); 
$post->hotness = $rank->hotness($upvotes, $downvotes, strtotime($post->created_at)); 
$post->save(); 

如果有更好的方法來做到這一點,請讓我知道。