Laravel的findOrFail返回所有记录。

3

不确定为什么会出现这种情况。我之前用过这种方法,一切都运行良好。但是某些原因导致findOrFail没有将where子句添加到要执行的查询中。有其他人遇到过这种问题吗?我可以使用Model::where()方法,但如果有问题或者我漏掉了什么,我想找出原因。

路由:

Route::get('/forums/topic/{id}/post/create', 'ForumController@topicPostCreate');

控制器:


<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Image;
use App\PostImage;
use Auth;
use App\Topic;
use App\Post;
use App\Http\Requests\SearchRequest;
use App\Http\Requests\PostImageRequest;
use App\Http\Requests\PostRequest;
use App\Http\Requests\TopicRequest;
use App\Http\Controllers\Controller;


class ForumController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }


    /**
     * Show the form for creating a new topic.
     *
     * @return \Illuminate\Http\Response
     */
    public function topicPostCreate($id)
    {
        $results = Topic::findOrFail($id)->toSql();
        dd($results);

    }

}

模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Topic extends Model
{
    protected $fillable = [
        'title',
        'user_id'
    ];

    /**
     * Many topics belong to one user
     */
    public function user(){

        return $this->belongsTo('App\User');

    }

    /**
     * Each Topic has many posts
     * 
     */
    public function posts()
    {
        return $this->hasMany('App\Post');
    }

}

从dd()函数返回的查询语句如下:
"select * from `topics`"

有人知道为什么会发生这种情况吗?一定有一个很好的理由。也许是我漏掉了什么......???

1个回答

2

findOrFail 返回一个新的、填充了空查询的 Topic 实例。这就是为什么你没有看到任何 where,因为具有这些内容的查询已经被执行了。

如果你想查看实际运行的查询,可以尝试监听数据库查询(只需将此放在 routes.php 中暂时使用)。

\DB::listen(function($sql) {
    dump($sql);
});

1
抢了我的台词。顺便提一下,https://github.com/barryvdh/laravel-debugbar 对于监控执行的查询也非常方便。 - ceejayoz
同意,调试栏非常多才多艺! - rdiz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接