2015-10-20 151 views
1

我不明白,为什么结果是如此的不同获取相关数据: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 

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

回答

4

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