Kam*_*ame 7 php mysql join laravel
我的问题是在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`)
);
Run Code Online (Sandbox Code Playgroud)
现在,我需要加入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();?>
Run Code Online (Sandbox Code Playgroud)
加入这些表非常简单,好的.但我的问题是表名是动态的.
<?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();
?>
Run Code Online (Sandbox Code Playgroud)
请帮我解决这个问题.非常感谢!!!
maj*_*rif 10
您需要将变量从本地范围导入到匿名函数的范围,这是如何:
$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();
Run Code Online (Sandbox Code Playgroud)
注意这一行:
->join('links', function($join) use ($table)
Run Code Online (Sandbox Code Playgroud)
问题是匿名函数不知道变量$table
,所以你告诉它使用变量use
.
您可以在文档中找到它.
归档时间: |
|
查看次数: |
2772 次 |
最近记录: |