2014-08-27 73 views
12

我需要将此查询转换为Laravel,并且我尝试使用Laravel的Eloquont ORM或查询创建Insert ... Select语句时出现问题。我不知道如何去创建这个查询。在Laravel中创建插入... Select语句

Insert into Demand (Login, Name, ApptTime, Phone, Physician, Location, FormatName, FormatDate, FormatTime, ApptDate, FormatPhone, cellphone) 
Select Login, Name, ApptTime, Phone, Physician, Location, FormatName, FormatDate, FormatTime, ApptDate, FormatPhone, cellphone from " . [dbname] . " 
    Where " . $where_statement 

如何使用Laravel的ORM创建此查询?

编辑:我不知道这是明确的,但我想在1个查询而言,就像他们在这里做http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

+0

请到通过文档,这可能会更有帮助:http://laravel.com/docs/eloquent – 2014-08-27 18:44:54

+0

我已经通过文档,并尝试了不同的链。但我仍然不确定如何创建这个作为一个查询与2. – jamadri 2014-08-27 19:09:37

+0

雄辩不是真的意味着照顾这样的事情。你可以把查询放在'DB :: statement()'里面。 – user3158900 2014-08-27 20:29:50

回答

26

在一个查询中没有办法做到这一点,但我遇到了同样的问题,并希望确保我可以继续使用QueryBuilder构建的特定选择。

所以,你可以做些什么,让事情变得半是什么干净,再用这之前已经建立了一个select语句的功能,是这样的:

/** 
* Wherever your Select may come from 
**/ 
$select = User::where(...) 
        ->where(...) 
        ->whereIn(...) 
        ->select(array('email','moneyOwing')); 
/** 
* get the binding parameters 
**/ 
$bindings = $select->getBindings(); 
/** 
* now go down to the "Network Layer" 
* and do a hard coded select, Laravel is a little 
* stupid here 
*/ 
$insertQuery = 'INSERT into user_debt_collection (email,dinero) ' 
       . $select->toSql(); 

\DB::insert($insertQuery, $bindings); 
+0

对于Laravel 5.3来说也是完美的作品 – Prashant 2017-07-07 07:59:24

+0

这真的很棒。 – caro 2018-02-17 20:55:01

0

首先,你需要创建一个模型Demand,所以那么你可以使用:

$demand = new Demand; 
$demand->Login = $login; 
$demand->Name = $name; 
[...] 
$demand->save(); // <~ this is your "insert" statement 
$id = $demand->id; 

那么对于你的SELECT语句,你可以做一些类似这些选项的东西:

$demand = Demand::find($id); // will be similar to: SELECT * FROM Demand WHERE `id` = '$id'; 
$demand = Demand::where('id', $id)->get(); //same as above 
$demand = Demand::where('id', $id)->get(array('Login', 'Name')); // will be similar to: SELECT `Login`, `Name` FROM Demand WHERE `id` = '$id'; 

有一个在很多的更多信息手册herehere

+0

select语句是插入的一部分。我已经通过了文档,但我没有看到如何做这样的事情:http://dev.mysql.com/doc/refman/5.0/en/insert-select.html 有没有办法在Laravel中使用一个查询来做到这一点?我知道我会如何做2,但这需要一分钟。我想知道是否有已经建立的东西来创建这一个查询。 – jamadri 2014-08-27 19:06:10

+0

我不认为你可以在雄辩ORM中做到这一点...但我可能是错的 – 2014-08-27 19:18:56

+0

我一直无法找到一个方式,这是提出这个问题。 – jamadri 2014-08-27 19:35:24

8

您可以使用:

DB::insert("insert into contacts(contact_id,contact_type,account_id,created_at,updated_at) select f.id,'App\\Friend',f.account_id,f.created_at,f.updated_at from friends as f where f.id=?",[16]);