Laravel - 使用具有复合主键的表加入

时间:2014-04-23 04:54:39

标签: php mysql join laravel

我的问题是在Laravel框架中加入2个表。一个是动态名称表(它是一个变量),第二个是复合主键。我必须使用查询生成器而不是where()。请查看我的以下内容以获取详细信息:

我有两张桌子:

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();?>

加入这些表非常简单,好的。但我的问题是表名是动态的。

<?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();

?>

请帮我解决这个问题。 非常感谢!!!

2 个答案:

答案 0 :(得分: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();

注意这一行:

->join('links', function($join) use ($table)

问题是匿名函数不知道变量$table,所以你用use告诉它变量。

您可以在docs

中找到它

答案 1 :(得分:3)

请尝试:

<?php 
$type = Input::get('type', null);
$table = $type . '_details';
$joinFunction = function($join) use ($table)
                {
                    $join->on($table . '.source_id', '=',  'links.source_id');
                    $join->on($table . '.brand_id','=', 'links.brand_id');
                }
$results =  \DB::table($table)
                ->join('links',$joinFunction )
                ->get();

?>

问题是该函数没有在其中看到$ table变量。这就是你需要使用“use”语句的原因。

详细了解anonymous functions in php here

相关问题