[英]Laravel Eloquent: In many to many relationships the ORM is returning only one Object
我的表結構是這樣的:
技能
-ID
- 名稱
開口
-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;
}
如何使用數據透視表“ openings_skills”提取特定空缺的所有技能? PS:我的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);
});
我還使用了您提供的相同模型。 所以我認為您的問題可能出在您創建遷移的方式上。 讓我知道是否有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.