laravel - 在“if”条件下获取数据 laravel
问题描述
所以基本我有两个表“帐户”和“字符”,它们由一个 ID 链接每个“帐户”有 3 个“字符”所以我想显示链接到主“帐户”的 3 个字符
这是我的家庭控制器
{
$data = DB::table('characters')
->join('accounts', 'accounts.cUid', '=','characters.pUniqueID')->get();
return view('home', compact('data'));
}
这是我的家。刀片
@foreach($data as $per)
@if( $per->pUniqueID == Auth::user()->cUid )
....
....
@else
<script>window.location.href = '{{url("/characters")}}'; </script>
@endif
@endforeach
解决方案
在模型中配置关系:
Accounts.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Accounts extends Model
{
public function characters()
{
return $this->hasMany('App\Characters');
}
}
因此,在您的查询中:
$data = Accounts::with("characters")->get();
return view('home', compact('data'));
在您的模板中:
@foreach($data as $per)
@if($per->pUniqueID == Auth::user()->cUid)
@foreach($per->characters as $character)
{{$character->id}} //or any other character attribute
@endforeach
@else
<script>window.location.href = '{{url("/characters")}}'; </script>
@endif
@endforeach
推荐阅读
- getstream-io - 在聚合提要中为 strftime 使用不同的时区
- firebase - 在非订单 Firestore 查询中使用偏移量对数据进行分页
- sql - 在 oracle 中仅显示 SQL 查询的最大结果
- android - Android Navigation 库深度链接:如何合成 backstack
- html - 元刷新在 Mozilla 和 IE 上不起作用
- angularjs - Hyperledger Angular App - 错误消息:“找不到 API 路由”
- regex - 如果一行以 = 结尾,则追加下一行 (sed)
- api - 如何检索 Planner 任务注释以在 PowerApps 中使用
- linkedin - 安装 Linkedin 的 WhereHows 后凭据无效
- docker - 在 Windows 中使用 Docker 安装 CI gitlab