【问题标题】:Laravel get data from 2 tables where not nullLaravel 从 2 个不为空的表中获取数据
【发布时间】:2016-01-01 03:33:04
【问题描述】:

我正在尝试从两个不同的表中获取一些数据,

所以它现在看起来像这样:

但我不希望显示空字段(Globale-Moderator、Moderator 和 Proef-Moderator)。我怎么能用这段代码做到这一点;

控制器:

public function ForumTeam()
    {
        $roles = Role::where('id', '>', '4')->orderBy('id', 'DESC')->get();
        return View::make('team')->with('roles', $roles);
    }

查看:

<div class="panel-group col-sm-offset-1 col-sm-10">
  @foreach($roles as $role)
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">{{ $role->name }}</h3>
      </div>
      <div class="panel-body">
        <ul class="list-group">

          @foreach($role->user as $user)
            <li class="list-group-item">
              <img src="{{ Config::get('app.url') }}/public/img/avatar.jpg" style="float:left;margin-right:15px;padding-bottom:5px;" class="img-circle" alt="{{ $user->username }}" width="75" height="75">
              <h4 style="color:{{ $role->colour }};"><strong>{{ $user->username }}</strong></h4>
              <p>{{ $user->usertitle }}</p>
            </li>
          @endforeach

        </ul>
      </div>
    </div>
  @endforeach
</div>

所以我想隐藏未填写的字段,我应该怎么做?

我的另一个选择是在“空”字段内显示一些文本。就像“没有人拥有这个级别”。

谢谢!

【问题讨论】:

    标签: php laravel-4 role


    【解决方案1】:

    您可以/应该能够使用:

    @foreach($roles as $role)
    
       @if($role->user != null || !empty($role->user->name))
    
       @endif
    
    @endforeach
    

    然后您可以检查role-&gt;user 是否为 NOT NULL 或角色名称是否为空。其中 name 是角色名称,即“Admin”、“Moderator”

    或者,尝试:

      @foreach($roles as $role)
    
        @if(count($role->user) >= 1)
           // Do stuff
        @endif
    
      @endforeach
    

    由于您得到User,它具有一对多关系,因此会有多个用户。

    【讨论】:

    • @RobinR 不用担心。提示:如果你dd($roles),你可以看到数据是如何分布的。然后你可以点击关系,看看有 4 个,例如,看看它们是否包含空对象。从而给你你正在寻找的答案:)
    • 哦,好的,谢谢您的提示!我没想到这么远:)
    【解决方案2】:

    您可以在第一个 @foreach 之后添加 if 语句,以检查角色是否 有用户,

    @foreach($roles as $role)
        @if(isset($role->user))
        ...
        @endif
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 2016-06-24
      • 2017-04-02
      • 2019-09-10
      • 1970-01-01
      相关资源
      最近更新 更多