我在Laravel中建立了多对多的关系,并在数据库表中填充了数据。关系设置看起来像这样......
users.php
---------
public function houses()
{
return $this->belongsToMany('App\House')
->withTimestamps();
}
house.php
---------
public function users()
{
return $this->belongsToMany('App\User')
->withTimestamps();
}
在我的/house/show.blade.php中我试图像这样显示已保存的连接......
$houses = House::with('App\User')->all();
foreach ($houses as $house) {
echo 'Found House';
}
它给我一个错误,说无法找到$ house。我哪里错了?
答案 0 :(得分:4)
您应该在with
方法中指明这样的关系:
$houses = House::with('users')->get();
还有一件事情是让控制器中的房子更好并将它们传递给视图:
$houses = House::with('users')->get();
return view('someView')->withHouses($houses);
在视图中这样做:
@foreach ($houses as $house)
{{ $house->addres }}
@endforeach
只有房子才能让用户试试这个:
$houses = House::has('users')->get();
要为用户添加一些条件,您可以这样做:
$houses = House::whereHas('users', function ($query) {
$query->where('name', 'some user name'); // to add some conditions on the user :)
})->get();
答案 1 :(得分:2)
你应该试试这个:
$houses = House::with('users')->get();
foreach ($houses as $house) {
echo 'Found House';
}
或强>
在控制器中:
use House;
$houses = House::with('users')->get();
return view('someView',compact('houses'));
在Blade文件中:
@foreach ($houses as $house)
{{ $house->name }}
@endforeach