Eloquent with declared table to use in the query

与世无争的帅哥 提交于 2019-12-13 06:59:54

问题


Given Larvel 5.2 and a SQL Server 2005 database. I have query something like this:

declare @mapping_table table(id int, name varchar(255), mapping_value varchar(255))

insert into @mapping_table values (1, 'foo', 'A1')
insert into @mapping_table values (2, 'bar', 'A1')
insert into @mapping_table values (3, 'baz', 'A2')

select distinct(lookup_field) 
from production_table
where lookup_field not in (
  select name
  from @mapping_table 
)

When I run this using Eloquent like so: DB::connection('sqlsrv')->select($query) I get the error The active result for the query contains no fields.

Background: I'm creating an app that ensures certain queries result in a valid result set for reporting purposes. Mostly these ara data mappings for free text input to a defined list of options. If a new free text entry is found in the production a query should mention the unmapped value(s) so I can add them to the defined table.

I have no writing access on the production database, only read. Creating stored procedures is not an option due to this limitation. When I copy the query to SQL Server Management Studio it works like charm. I'm guessing this is because SSMS internally seperates the results and Eloquent doesn't.

How can I get a query like the given one get to work with Eloquent?


回答1:


Pure guesswork, but does eloquent require column names ?

Try

Select distinct(lookup_field) as lookup_field



回答2:


I just tried the command below on my Tinker and it worked fine. Remember to include "SET NOCOUNT ON" and format to use just one line.

DB::connection()->select("SET NOCOUNT ON; declare @mapping_table table(id int, name varchar(255), mapping_value varchar(255)); insert into @mapping_table values (1, 'foo', 'A1'); insert into @mapping_table values (2, 'bar', 'A1'); insert into @mapping_table values (3, 'baz', 'A2'); select distinct lookup_field from production_table where lookup_field not in (select name  from @mapping_table)");


来源:https://stackoverflow.com/questions/36743040/eloquent-with-declared-table-to-use-in-the-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!