返回 Laravel 中非空的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43309905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:45:44  来源:igfitidea点击:

return rows in laravel that are not empty

phpjsonlaravelselect

提问by Johnny

I have the following output that I am getting from the laravel and I am inserting them in to selectbox as an option. But for the lunch optionmy last options are empty. How can I return rows in laravel that are not empty?

我有以下从 laravel 获得的输出,我将它们作为选项插入到选择框中。但是对于lunch option我的最后一个选项是空的。如何在 Laravel 中返​​回非空行?

{"id":18,"guest_origin":"Bulgaria","heard_where":"","staying_at":"","lunch_option":"Cheese"},{"id":19,"guest_origin":"Chech Republic","heard_where":"","staying_at":"","lunch_option":"Chicken"},{"id":20,"guest_origin":"China","heard_where":"","staying_at":"","lunch_option":"Ham"},{"id":21,"guest_origin":"Denmark","heard_where":"","staying_at":"","lunch_option":""},{"id":22,"guest_origin":"Finland","heard_where":"","staying_at":"","lunch_option":""},{"id":23,"guest_origin":"Israel","heard_where":"","staying_at":"","lunch_option":""},{"id":24,"guest_origin":"Malaysia","heard_where":"","staying_at":"","lunch_option":""},{"id":25,"guest_origin":"Norway","heard_where":"","staying_at":"","lunch_option":""},

{"id":18,"guest_origin":"保加利亚","heard_where":"","staying_at":"","lunch_option":"奶酪"},{"id":19,"guest_origin":" Chech Republic","heard_where":"","staying_at":"","lunch_option":"Chicken"},{"id":20,"guest_origin":"China","heard_where":""," stay_at":"","lunch_option":"Ham"},{"id":21,"guest_origin":"丹麦","heard_where":"","staying_at":"","lunch_option":"" },{"id":22,"guest_origin":"芬兰","heard_where":"","staying_at":"","lunch_option":""},{"id":23,"guest_origin":"Israel","heard_where":"","staying_at":"","lunch_option":""},{"id ":24,"guest_origin":"马来西亚","heard_where":"","staying_at":"","lunch_option":""},{"id":25,"guest_origin":"挪威","听说哪里":"","staying_at":"","lunch_option":""},"heard_where":"","staying_at":"","lunch_option":""},{"id":25,"guest_origin":"挪威","heard_where":"","staying_at":"" ,"lunch_option":""},"heard_where":"","staying_at":"","lunch_option":""},{"id":25,"guest_origin":"挪威","heard_where":"","staying_at":"" ,"lunch_option":""},

enter image description here

在此处输入图片说明

controller.php

控制器.php

function getComboselect( Request $request)
{
    if($request->ajax() == true && \Auth::check() == true)
    {
        $param = explode(':',$request->input('filter'));
        $parent = (!is_null($request->input('parent')) ? $request->input('parent') : null);
        $limit = (!is_null($request->input('limit')) ? $request->input('limit') : null);
        $rows = $this->model->getComboselect($param,$limit,$parent);
        $items = array();
        $fields = explode("|",$param[2]);
        foreach($rows as $row) 
        {
            $value = "";
            foreach($fields as $item=>$val)
            {
                if($val != "") $value .= $row->{$val}." ";
            }
            $items[] = array($row->{$param['1']} , $value);     
        }
    return json_encode($items);     
    } 

Model.php

模型.php

static function getComboselect( $params , $limit =null, $parent = null)
{   
    $limit = explode(':',$limit);
    $parent = explode(':',$parent);
    if(count($limit) >=3)
    {
        $table = $params[0]; 
        $condition = $limit[0]." `".$limit[1]."` ".$limit[2]." ".$limit[3]." "; 
        if(count($parent)>=2 )
        {
            $row =  \DB::table($table)->where($parent[0],$parent[1])->get();
             $row =  \DB::select( "SELECT * FROM ".$table." ".$condition ." AND ".$parent[0]." = '".$parent[1]."'");
        } else  {
           $row =  \DB::select( "SELECT * FROM ".$table." ".$condition);
        }        
    }else{
        $table = $params[0]; 
        if(count($parent)>=2 )
        {
            $row =  \DB::table($table)->where($parent[0],$parent[1])->get();
        } else  {
            $row =  \DB::table($table)->get();
        }              
    }
    return $row;
}

This code is using http://carlosdeoliveira.net/jcombo/?lang=en. If you look up to the example on the project link you will see that it is using parent (state) to list the child (cities) for listings. I am not using the parent so nothing is assinged to variables $parent[0] and $parent[ 1 ], thus nothing to worry about but for the rest, I will try to post each result below so, you would have a better idea. My understanding is that the model.php is passing the data to controllers.php using $row = \DB::table($table)->get();If you look to the screenshot, you will see that I have more then 1 column to list the options. I cannot write a single column name there if I write $row = \DB::table($table)->whereRaw('lunch <> ""')->get();this brings the options until the Id 4. In this case Holland is not in the option list for guest origin.

此代码使用http://carlosdeoliveira.net/jcombo/?lang=en。如果您查看项目链接上的示例,您将看到它正在使用父(州)列出子(城市)以进行列表。我没有使用父级,所以没有任何东西分配给变量 $parent[0] 和 $parent[1],因此没什么好担心的,但对于其余的,我会尝试在下面发布每个结果,这样你会有更好的主意. 我的理解是 model.php 正在将数据传递给controllers.php 使用 $row = \DB::table($table)->get();如果您查看屏幕截图,您会看到我有超过 1 列来列出选项。如果我$row = \DB::table($table)->whereRaw('lunch <> ""')->get();这样写,我就不能在那里写一个列名,直到 Id 4。在这种情况下,Holland 不在来宾来源的选项列表中。

Once the model.php passes $rowto controllers.php, It' returning the following results for each variable.

一旦model.php 传递$row给controllers.php,它就会为每个变量返回以下结果。

print_r($row);

stdClass Object ( [id] => 48 [guest_origin] => Other [heard_where] => [staying_at] => [lunch_option] => )

stdClass 对象([id] => 48 [guest_origin] => 其他 [heard_where] => [staying_at] => [lunch_option] =>)

print_r($rows);

Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [id] => 1 [guest_origin] => Western Australia [heard_where] => Wildsights Office [staying_at] => Wildsights Villas [lunch_option] => Chicken ) 1=> stdClass Object ( [id] => 2 [guest_origin] => Rest of Australia [heard_where] => Brochure [staying_at] => Wildsights Beach Units [lunch_option] => Cheese ) [2] => stdClass Object ( [id] => 3 [guest_origin] => Germany & Austria [heard_where] => Sign [staying_at] => Bay Lodge Backpackers [lunch_option] => Ham ) [3] => stdClass Object ( [id] => 4 [guest_origin] => UK & Eire [heard_where] => Word of Mouth [staying_at] => Blue Dolphin Caravan Park [lunch_option] => Tuna )

Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [id] => 1 [guest_origin] => 西澳大利亚 [heard_where] => Wildsights Office [staying_at] => Wildsights别墅 [lunch_option] => Chicken ) 1=> stdClass Object ( [id] => 2 [guest_origin] => 澳大利亚其他地区 [heard_where] => 手册 [staying_at] => Wildsights Beach Units [lunch_option] => Cheese) [ 2] => stdClass 对象( [id] => 3 [guest_origin] => 德国和奥地利 [heard_where] => 签名 [staying_at] => Bay Lodge Backpackers [lunch_option] => Ham )[3] => stdClass 对象( [id] => 4 [guest_origin] => 英国和爱尔兰 [heard_where] => 口碑 [staying_at] => Blue Dolphin Caravan Park [lunch_option] => 金枪鱼)

print_r($fields);

Array ( [0] => staying_at )

数组 ( [0] =>stay_at )

print_r($value); 

prints nothing

什么都不打印

print_r($items);

[8] => Array ( [0] => Shark Bay Holiday Cottages 1=> Shark Bay Holiday Cottages ) [9] => Array ( [0] => Shark Bay Hotel 1=> Shark Bay Hotel )

[8] => Array ( [0] => 鲨鱼湾假日小屋1=> 鲨鱼湾假日小屋 ) [9] => Array ( [0] => 鲨鱼湾酒店1=> 鲨鱼湾酒店 )

Hope it is clear and you can help me to filter the empty rows before it goes into loop.

希望很清楚,您可以帮助我在进入循环之前过滤空行。

回答by Clean code

The most appropriate way would be to use whereRawoperator rather then where.

最合适的方法是使用whereRawoperator 而不是where

e.x The following query will fetch all data except empty("")values in the field list.

ex 以下查询将获取("")字段列表中除空值之外的所有数据。

DB::table('mytable')->whereRaw('field <> ""')->get();

回答by SpinyMan

You can use macro, it checks field for not null and not empty string. Just add these lines of code into your AppServiceProvider

您可以使用宏,它会检查字段是否为非空和非空字符串。只需将这些代码行添加到您的 AppServiceProvider 中

use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;

public function boot()
{
    QueryBuilder::macro(
        'whereNotEmpty',
        function (string $column) {
            return $this->whereNotNull($column)
                ->where($column, '<>', '');
        }
    );

    EloquentBuilder::macro(
        'whereNotEmpty',
        function (string $column) {
            return $this->getQuery()
                ->whereNotEmpty($column);
        }
    );
}

And now you allow to use this like that:

现在你允许这样使用它:

$posts = Post::whereNotEmpty('field')->get();