繁体   English   中英

Laravel Eloquent:在许多关系中,ORM只返回一个对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM