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


Laravel - Get related data with find method (for one record)

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

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

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

where()返回一个查询生成器对象(您可以在执行getfirst之前添加额外的条件)

从源代码:

/**
 * 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;
}

另一方面,find只返回实际模型或模型集合(不是查询生成器)。

从源代码:

/**
 * 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);
}

查看api文档:http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Builder.html

只有返回$this(Builder)的雄辩方法才能在管道中用于添加要选择的规则