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

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

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

Look at api documentations: http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Builder.html

only eloquent methods that returns $this(Builder) can be used in pipe for adding rules what to select.