dongya5893 2015-10-20 14:29 采纳率: 100%
浏览 1869
已采纳

Laravel - 使用find方法获取相关数据(对于一条记录)

我不明白为什么结果会如此不同:

Shop::find($id)->with('products'); // just empty

Shop::find($id)->with('products')->first(); // ignores find()

但同样的事情 where() 起作用了。

Shop::where('id', $id)->with('products')->first(); // works fine

那么,最后一条是正确的方法吗?(如果我只是想要一个附带产品的商店)

  • 写回答

2条回答 默认 最新

  • duanjia2415 2015-10-20 14:33
    关注

    where() returns a query builder object (which you can add extra terms to before executing with get or first)

    From the source code:

    /**
     * Add a basic where clause to the query.
     *
     * @param  string  $column
     * @param  string  $operator
     * @param  mixed   $value
     * @param  string  $boolean
     * @return $this
     */
    public function where($column, $operator = null, $value = null, $boolean = 'and')
    {
        if ($column instanceof Closure) {
            $query = $this->model->newQueryWithoutScopes();
    
            call_user_func($column, $query);
    
            $this->query->addNestedWhereQuery($query->getQuery(), $boolean);
        } else {
            call_user_func_array([$this->query, 'where'], func_get_args());
        }
    
        return $this;
    }
    

    On the other hand, find just returns the actual model or a collection of models (not a query builder).

    From the source code:

    /**
     * Find a model by its primary key.
     *
     * @param  mixed  $id
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null
     */
    public function find($id, $columns = ['*'])
    {
        if (is_array($id)) {
            return $this->findMany($id, $columns);
        }
    
        $this->query->where($this->model->getQualifiedKeyName(), '=', $id);
    
        return $this->first($columns);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面