Laravel 5.2 Elequent ORM保存()不工作

Laravel 5.2 Elequent ORM保存()不工作

问题描述:

我称之为列辣味帖子表,我试图用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(); 

当我运行此命令并检查我的数据库后,后热度仍然在起始值。两个回显都会打印出正确的值,并且不会出现错误。任何想法为什么它没有更新?

我想通了。事实证明,你不能在你正在更新的模型上使用'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(); 

如果有更好的方法来做到这一点,请让我知道。