2014-10-19 67 views
1

我的表结构是这样的:
技能
-id
- 命名Laravel雄辩:在多对多relatioships的ORM将返回只有一个对象

开口
-id
....

openings_skills
-id
-opening_id
-skill_id

这些是我的两个模型。

class Skill extends Eloquent { 
protected $table = 'skills'; 
public function opening() { 
    return $this->belongsToMany('Opening', 'openings_skills'); 
} 
} 


class Opening extends Eloquent { 
protected $table = 'openings'; 
public function skill() { 
    return $this->belongsToMany('Skill', 'openings_skills'); 
} 
} 

当我尝试使用下面的代码来获取数据,我只在收集这么迭代得到单个对象在它给了我一个技能名。

$opening = Opening::find($id); 
    foreach($opening->skill as $skill){ 
     echo $skill; 
    } 

我该如何使用pivot_table'openings_skills'来提取特定开放的所有技能? P.S:我为我的网络应用程序使用Laravel 4.9.11版本。

回答

0

所以我这个尝试自己,这里的工作代码我使用:

<?php 

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreateSkillsTable extends Migration { 

/** 
* Run the migrations. 
* 
* @return void 
*/ 
public function up() 
{ 
    Schema::create('skills', function($table){ 
     $table->increments('id'); 
     $table->string('name'); 
     $table->timestamps(); 
    }); 
} 

/** 
* Reverse the migrations. 
* 
* @return void 
*/ 
public function down() 
{ 
    Schema::drop('skills'); 
} 

} 

<?php 

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreateOpeningsTable extends Migration { 

/** 
* Run the migrations. 
* 
* @return void 
*/ 
public function up() 
{ 
    Schema::create('openings', function($table){ 
     $table->increments('id'); 
     $table->string('opening'); 
     $table->timestamps(); 
    }); 
} 

/** 
* Reverse the migrations. 
* 
* @return void 
*/ 
public function down() 
{ 
    Schema::drop('openings'); 
} 

} 

<?php 

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreateOpeningsSkillsTable extends Migration { 

/** 
* Run the migrations. 
* 
* @return void 
*/ 
public function up() 
{ 
    Schema::create('openings_skills', function($table) 
    { 
     $table->increments('id'); 
     $table->integer('skill_id')->unsigned()->index(); 
     $table->integer('opening_id')->unsigned()->index(); 
     $table->foreign('skill_id')->references('id')->on('skills')->onDelete('cascade'); 
     $table->foreign('opening_id')->references('id')->on('openings')->onDelete('cascade'); 
    }); 
} 

/** 
* Reverse the migrations. 
* 
* @return void 
*/ 
public function down() 
{ 
    Schema::drop('openings_skills'); 
} 

} 

//这里是我使用的路线。

Route::get('/', function() 
{ 
    $opening = Opening::find(1); 
    dd($opening->skill); 
}); 

我还使用了您提供的相同型号。所以我认为你的问题可能在于你如何创建迁移。 让我知道如果有帮助

0

也许你应该检查你的连接表中的外键值是否是正确的值?