首页 > 解决方案 > 在“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

标签: laravel

解决方案


在模型中配置关系:

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

推荐阅读