Laravel动态键和值查询编写

时间:2018-01-05 13:26:38

标签: php mysql laravel

我想在laravel中写这个查询,任何人都可以请帮助我。我是laravel的新手。

public function selectTableData($table,$condition)
{
    try{
        $query = "SELECT * from ".$table;
        if(is_array($condition))
        {
            $query .= " WHERE ";
            foreach ($condition as $key => $value) 
                $query .= $key . "= '".$value."' AND ";
            $query = rtrim($query,'AND ');
        }
        $result = mysql_query($query);
        if (!$result) 
            throw new Exception(mysql_error());
        if (mysql_num_rows($result) > 0) {
           return mysql_fetch_assoc($result);
        }
        else
            return false;
    } catch ( Exception $e ) {
            throw new Exception($e->getMessage ());
    }       
}

此外,我想以laravel查询格式编写此代码

public function insertTableData($table,$data)
{
    try{
        // generate insert query 
        if(is_array($data)){
            $query = 'INSERT INTO '. $table.' ( ';
            foreach ($data as $key => $value) 
                $query .= $key . ',';
            $query = rtrim($query,',');
            $query .= ') VALUES (';
            foreach ($data as $key => $value) 
                $query .= '"'.$value.'",';
            $query = rtrim($query,',');
            $query .= ')';
            $result = mysql_query($query); 
            //if (!$result) {
             //   throw new Exception( 'Could not run query: ' . mysql_error());
            //}
            return $result;
        }
        else
            return false;
    } catch ( Exception $e ) {
            throw new Exception($e->getMessage ());
    }   
}

如果它是胶囊形式,那么它将是好的

2 个答案:

答案 0 :(得分:1)

您可以在下面的laravel中编写此查询。

$query = DB::table($table);
if(is_array($condition)) {
    foreach ($condition as $key => $value) {
        $query->where($key, "'" . $value . "'");
    }
}
$result = $query->get();
if (count($result) > 0) {
    return $result;
} else {
    return false;
}

答案 1 :(得分:1)

我假设您的雄辩模型类是 SomeModel 。然后你可以尝试以下第一个查询/方法 -

$query = new SomeModel();
    if(is_array($condition))
    {
        foreach ($condition as $key => $value)
            $query = $query->where($key, $value);
    }
    $result = $query->get();

而对于第二个 -

if(is_array($data)){
        $query = new SomeModel();
        foreach ($data as $key => $value) 
            $query->$key = $value;
        $query->save();        
    }

希望它能解决你的问题:)