仅当当前字段不为空时才从数据库输出数据?

时间:2018-03-02 12:16:34

标签: php sql laravel

我在这里遇到一些问题: 如果数据库表中有条目,我只想输出内容。现在我的代码看起来像这样:

@foreach ($customers as $customer)
    <h2>{{$customer->name}} | {{$customer->company}}</h2>
    <div class="column-left">
        <p>ID: {{$customer->customer_id}}</p>
        <p>E-Mail: {{$customer->email}}</p>
        <p>Phone: {{$customer->phone}}</p>
    @if($customer->mobile != NULL)
        <p>Mobile: {{$customer->mobile}}</p>
    @else
    @endif
    </div>
@endforeach

我想我应该搜索输出当前字段名称的内容,以便它跳过空条目,例如,如果表中没有移动号码,则不输出。所以我的逻辑从一开始就存在缺陷。这导致我找到一个相当不美观的“解决方案”:

{{1}}

所以这确实有效。但理论上,我需要手动对每个数据库条目执行此操作,我不完全确定,如果该字段可能为空白。

有更好的解决方案吗?

2 个答案:

答案 0 :(得分:1)

我认为您可以使用array_filter

<?php
$data = array(
             0 => array(
                'name'=> '',
                'company'=>'companyName',
                'customer_id'=> 123456,
                'phone'=> '11111',
            ),
             1 => array(
                'name'=> 'Tom',
                'company'=>'',
                'customer_id'=> 123457,
                'phone'=> '11112',
            ),
             2 => array(
                'name'=> 'Daniel',
                'company'=>'companyName',
                'customer_id'=> '',
                'phone'=> '11113',
            ),
             3 => array(
                'name'=> 'Bob',
                'company'=>'companyName',
                'customer_id'=> 123458,
                'phone'=> '',
            ),
             4 => array(
                'name'=> 'Amy',
                'company'=>'companyName',
                'customer_id'=> '123456',
                'phone'=> '11114',
            ),
          );
$customers = array();
foreach ($data as $value) {
    array_push($customers,array_filter( $value));
}
print_r($customers);
return $customers;

以上示例将输出:

Array
(
    [0] => Array
        (
            [company] => companyName
            [customer_id] => 123456
            [phone] => 11111
        )

    [1] => Array
        (
            [name] => Tom
            [customer_id] => 123457
            [phone] => 11112
        )

    [2] => Array
        (
            [name] => Daniel
            [company] => companyName
            [phone] => 11113
        )

    [3] => Array
        (
            [name] => Bob
            [company] => companyName
            [customer_id] => 123458
        )

    [4] => Array
        (
            [name] => Amy
            [company] => companyName
            [customer_id] => 123456
            [phone] => 11114
        )
)

答案 1 :(得分:0)

在客户模型上,您可以将逻辑放在那里,例如;

public function hasMobile() {
    if($this->mobile){
        return '<p>Mobile: ' . $this->mobile . '</p>';
    }

    return null;
}

对于您要显示/不显示的每个项目执行此操作,然后在视图中,您可以每次引用该内容,而不是在x个视图中使用if语句。如果你需要更新它,更新一个它们都会改变

也会很好

查看就像;

    {{ $customer->hasMobile() }}

最有可能是更好的方法,但这是我想要的选择。

相关问题