简体   繁体   English

Laravel 4无法访问select :: db的值

[英]Laravel 4 can't access a value of select::db

I'm querying DB in laravel 4 but can't access the returned value here is the code : 我在laravel 4中查询数据库,但无法访问返回的值,这里是代码:

public static function getCityIdByName($cityname){
    $cityid = DB::select( DB::raw(" SELECT id  FROM cities WHERE match(city_name) against('*" .
        $cityname . "*' IN BOOLEAN MODE ) " ));

    return $cityid;
}

so the function returns this [{"id":1}] and I need to get value "1", I tried $cityid->id and $cityid['id'] and $cityid[0] but it all returns an error , also it is not a string , when I echo it, it complains that array is not a string Array to string conversion 所以该函数返回此[{"id":1}] ,我需要获取值“ 1”,我尝试了$cityid->id$cityid['id']$cityid[0]但它们都返回了错误,它也不是字符串,当我回显它时,它抱怨数组不是字符串Array to string conversion

I solved the problem with this code : 我用以下代码解决了问题:

return $cityid[0]->id;

thanks to @ Sylwit 感谢@ Sylwit

Even if it works you can improve it 即使有效,您也可以改善它

If you have several results you would take only the first of the array while you would maybe take care of all results. 如果有多个结果,则只处理数组的第一个,而可能要处理所有结果。

You can also use ->first() in your query to get only the first object which will avoid you to use the [0]. 您还可以在查询中使用->first()来仅获取第一个对象,从而避免使用[0]。

An interesting link https://laracasts.com/discuss/channels/eloquent/is-this-match-against-using-relevance-possible 一个有趣的链接https://laracasts.com/discuss/channels/eloquent/is-this-match-against-using-relevance-possible

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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