使用Laravel Relations
时如何使用Query Builders
?
$Cars = User::find(1)->car; // works well and returns all cars
$User = User::where('username' , 'John')->get();
$Cars = $User->car; // doesn't work.
任何帮助。 感谢
解决
$User = User::where('username' , 'John')->get();
应该
$User = User::where('username' , 'John')->first(); // to get an object instead of array
答案 0 :(得分:1)
::find()
方法将返回模型的实例,允许您访问模型上设置的关系等。
即使从数据库中只选择了1行,->get()
方法也会返回Illuminate\Database\Eloquent\Collection
个结果。
使用该集合,您可以遍历结果
$collection->each(function($model)
{
// You can now access $model->cars
});
另外,您可以使用->first()
,->last()
和::find()
方法返回模型的单个实例,以便您直接访问关系。
$model = Model::where('foo', 'bar')->first(); // Returns first row from the database
$model->cars // Is now accessable
答案 1 :(得分:0)
假设您已经拥有了Cars类,那么您只需要在User类中添加方法。
//add this method to your User class
public function cars()
{
//since you'll be using many to many
//you might use `user_cars` as pivotal table
return $this->belongsToMany('Cars', 'user_cars', 'cars', 'cars');
}
您可以使用以下方式调用它:
User::find(1)->cars()->get();