Php Laravel雄辩:在多对多关系中,ORM只返回一个对象
我的表结构如下:Php Laravel雄辩:在多对多关系中,ORM只返回一个对象,php,orm,laravel-4,many-to-many,eloquent,Php,Orm,Laravel 4,Many To Many,Eloquent,我的表结构如下: 技能 -id -名字 空缺 -id 职位空缺与技能 -id -打开\u id -技能id 这是我的两个模型 class Skill extends Eloquent { protected $table = 'skills'; public function opening() { return $this->belongsToMany('Opening', 'openings_skills'); } } class Opening extends Eloq
技能
-id
-名字 空缺
-id
职位空缺与技能
-id
-打开\u id
-技能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;
}
如何使用数据透视表“openings\u skills”提取该特定开口的所有技能?
注:我的web应用程序使用的是Laravel 4.9.11版本。
也许你应该检查外键值是否是联接表中的正确值?
所以我自己也尝试过,下面是我使用的工作代码:
<?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);
});