简体   繁体   中英

Laravel Query how to check if column starts with 0

I have a CRUD application with a Registration table and a Category table. In the RegistrationController , I use a query with Category, so I have made another query. I struggled with checking if every other gender_id has a cte_from that starts with 0. The cte_gender_id has 1, 2, or 3. 1 = man, 2 = women 3 = undetermined and nd cte_from are age ranges.

So in the database: cte_gender_id is 1 and cte_from is 0 then anther row cte_gender_id is 1 and cte_from is 25 then another cte_gender_id is 1 and 35 and so on but with gender_id 2 and 3.

RegistrationController

$gender_ids = ['1', '2', '3'];
foreach ($gender_ids as $gender_id) {
    $category = Categorie::where('cte_distance_id', $distance_id)
        ->where('cte_gender_id', $gender_id)
        ->where('cte_from',)
        ->first();
    
    if (is_null($category)) {
        return back()->with("errorMessage", "Category not found");
    }
}

So I want if, for example, where gender_id is 1 and cte_from doesn't start with 0, it already doesn't go through.

You can use WHERE cte_from LIKE '0%' to test if a string starts with 0 .
In this query, % is used for a wildcard.

Or in Laravel query builder:

->where('cte_from', 'LIKE', '0%')

// Or if it doesn't start with a 0
->where('cte_from', 'NOT LIKE', '0%')

try..

->where('cte_from', 'LIKE', '0%')

$gender_ids = ['1', '2', '3'];
    foreach($gender_ids as $gender_id){
        $category = Categorie::where('cte_distance_id', $distance_id)
        ->where('cte_gender_id', $gender_id)
        ->where('cte_from', 'LIKE', '0%')
        ->first();
        if(is_null($category)){
            return back()->with("errorMessage", "Category not found");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM