Php 使用多个表之间的关系从多个表中检索数据
我有一个表我需要完成,现在,它有3列日期,班次和车站 我只想要附加到登录用户的数据。Php 使用多个表之间的关系从多个表中检索数据,php,laravel,eloquent,Php,Laravel,Eloquent,我有一个表我需要完成,现在,它有3列日期,班次和车站 我只想要附加到登录用户的数据。 我有一个数据透视表,可以从中调用日期和班次的数据,但Stations是一个单独的表 我的数据透视表显示用户和班次之间的多对多关系,称为shift\U USER。这很有效, STATIONS表关系是与用户的一对多关系 因为一个用户将属于一个站点,但一个站点将有多个用户 电台型号 public function user() { return $this->hasMany('App\User'); }
我有一个数据透视表,可以从中调用日期和班次的数据,但Stations是一个单独的表 我的数据透视表显示用户和班次之间的多对多关系,称为shift\U USER。这很有效, STATIONS表关系是与用户的一对多关系 因为一个用户将属于一个站点,但一个站点将有多个用户 电台型号
public function user()
{
return $this->hasMany('App\User');
}
public function station()
{
return $this->belongsTo('App\Station');
}
}
用户模型
public function user()
{
return $this->hasMany('App\User');
}
public function station()
{
return $this->belongsTo('App\Station');
}
项目控制员
$user = Auth::user();
return view('layouts/timesheet/index', ['user' => $user]);
}
将信息放入表格的刀片视图
<table class="table table-sm table-success">
<tr>
<th scope="col">DATE/DAY</th>
<th scope="col">SHIFT</th>
<th scope="col">STATION</th>
</tr>
<tbody class="table-light">
@foreach ($user->Station as $station)
@endforeach
@foreach ($user->shifts as $shift)
<tr>
<td>{{ $shift->created_at }}</td>
<td>{{ $shift->Name }}</td>
<td>{{ $station->Name }}</td>
</tr>
@endforeach
日期/天
移位
站
@foreach($user->Station as$Station)
@endforeach
@foreach($user->shift as$shift)
{{$shift->created_at}
{{$shift->Name}
{{$station->Name}
@endforeach
这是我要填写的表格的图片。我想显示站点名称,但我只得到这个ID,我认为它是用户ID
请告诉我如何通过关系调用另一个表中的数据?
感谢您提供的任何帮助请确保您创建的函数与在Blade View上调用时的函数相同 Station.php
public function user()
{
return $this->belongsTo('App\User');
}
public function stations()
{
return $this->hasMany('App\Station');
}
User.php
public function user()
{
return $this->belongsTo('App\User');
}
public function stations()
{
return $this->hasMany('App\Station');
}
然后在“刀片视图”上,尝试以下操作:
@foreach($user as $u)
<tr>
<td>{{ $u->shift->created_at }}</td>
<td>{{ $u->shift->Name }}</td>
<td>{{ $u->stations->name }}</td> // I assume the column in stations table is "name"
</tr>
@endforeach
@foreach($u用户)
{{$u->shift->created_at}
{{$u->shift->Name}
{{$u->stations->name}//我假设stations表中的列是“name”
@endforeach
我现在收到这个错误:(……尝试读取boolIve上的属性“shifts”完成了,只需要将它添加到我的控制器中,然后我就可以从两个表调用数据,谢谢您的回复,我很感激。$user=Auth::user();$station=$user->station;模型还是一样吗?我的意思是一对多关系功能?是的,我没有真正改变模型,我保留了我最初发布的模型,但我为每个模型添加了外键,我不知道这是否有任何区别,但它是有效的,所以我将它们保留在:)