Laravel Can';t访问多对多关系中的数据
我有一个总线和路由模型试图通过总线访问路由,但得到错误 未定义的属性:stdClass::$route 控制器:Laravel Can';t访问多对多关系中的数据,laravel,model,many-to-many,Laravel,Model,Many To Many,我有一个总线和路由模型试图通过总线访问路由,但得到错误 未定义的属性:stdClass::$route 控制器: foreach ($Bus as $tBus){ foreach ($tBus->route as $tBusRoute) {//Undefined property: stdClass::$route if($tBusRoute->id == $rId){ $BusRout
foreach ($Bus as $tBus){
foreach ($tBus->route as $tBusRoute) {//Undefined property: stdClass::$route
if($tBusRoute->id == $rId){
$BusRouteId = $tBusRoute->pivot->id; }
}
}
巴士型号:
class Bus extends Model
{
protected $table = 'bus';
public $primaryKey = 'id';
public $timestamp = true;
public function route(){
return $this->belongsToMany(Route::class , 'bus_route' , 'bus_id' , 'route_id')->withPivot('id');
}
路线模型:
class Route extends Model
{
protected $table = 'route';
public $primaryKey = 'id';
public $timestamp = true;
public function bus(){
return $this->belongsToMany(Bus::class , 'bus_route' , 'route_id' , 'bus_id');
}
错误:未定义的属性:stdClass::$route您正在直接使用查询生成器,而不是通过Eloquent进行查询 要使用该模型,请执行以下操作:
$buses = Bus::where('transport_company_id', $tld)->get();
查询生成器返回stdClass
对象的集合,因此会出现错误。如果通过模型进行查询,将获得模型实例的集合
最好在人际关系中使用雄辩的语言
$Bus=Bus::with('route')->where('transport\u company\u id',$tId)->get()代码>首先,您使用的是,而不是,因此您的对象不会被强制转换为模型。请尝试以下方法:
$buses = Bus::where('transport_company_id', $tld)->get();
然后,您在$bus
集合中循环并调用关系,因此我建议您使用此值以避免:
注:鉴于公交车
可能有许多路线,您应该
将您的关系重命名为复数:routes
第三,您可以这样比较您的结果:
$buses = Bus::with('route')->where('transport_company_id', $tld)->get();
foreach($buses as $bus)
{
foreach($bus->route as $route)
{
// now you can get the $route instance with the pivot data:
dd($route->pivot->a_pivot_field);
}
}
您是如何获得$Bus
var的?似乎您直接使用了查询生成器,而不是雄辩的$Bus=DB::table('Bus')->where('transport_company_id',$tId)->get();我曾经this@Usuma汗。。是的,这就是原因。。因此,不要使用DB查询,而是使用这样的模型方法:$Bus=Bus::where('transport\u company\u id',$tId)->get();没问题,正如在其他答案中提到的,为了提高效率,您需要急切地加载关系<代码>总线::带('route')->…。
$buses = Bus::with('route')->where('transport_company_id', $tld)->get();
foreach($buses as $bus)
{
foreach($bus->route as $route)
{
// now you can get the $route instance with the pivot data:
dd($route->pivot->a_pivot_field);
}
}