我的问题是在 Laravel 框架中连接 2 个表。一个是动态名称表(它是一个变量),第二个是复合主键。我必须使用查询构建器而不是 where()。详情请看我的关注:
我有 2 个表:
CREATE TABLE `details` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`source_id` int(10) unsigned NOT NULL,
`brand_id` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `links` (
`source_id` int(10) unsigned NOT NULL,
`brand_id` tinyint(3) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`source_id`,`brand_id`)
);
现在,我需要加入 2 个这些表,我使用以下代码:
<?php $results = \DB::table('details')
->join('links', function($join)
{
$join->on('details.source_id', '=', 'links.source_id');
$join->on('details.brand_id','=', 'links.brand_id');
})
->get();?>
加入这些表很简单,OK。但我的问题是表名是动态的。
<?php
$type = Input::get('type', null);
$table = $type . '_details';
$results = \DB::table($table)
->join('links', function($join)
{
// the following code will show errors undefined $table
$join->on($table . '.source_id', '=', 'links.source_id');
$join->on($table . '.brand_id','=', 'links.brand_id');
})
->get();
?>
请帮我解决这个问题。 非常感谢!!!
最佳答案
您需要将变量从本地作用域导入到匿名函数的作用域中,方法如下:
$results = \DB::table($table)
->join('links', function($join) use ($table)
{
$join->on($table . '.source_id', '=', 'links.source_id');
$join->on($table . '.brand_id','=', 'links.brand_id');
})
->get();
注意这行:
->join('links', function($join) use ($table)
问题是匿名函数不知道变量 $table
,因此您使用 use
告诉它有关变量的信息。
您可以在 docs 中找到它.
关于php - Laravel - 加入具有复合主键的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23235031/