vendredi 1 avril 2016

Use Pivot Table query in Laravel 5.0

I'm using pivot table in my laravel 5.0 application, this is my database :

Temoignages

Schema::create('temoignages', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('personne_id')->unsigned();
        $table->foreign('personne_id')->references('id')->on('personnes');
        $table->text('temoignage');
        $table->double('note', 3, 1);
        $table->string('etat');
        $table->timestamps();
    });

Types

Schema::create('types', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('nom');
        $table->timestamps();
    });

So I have this pivot table generated :

Schema::create('temoignage_type', function (Blueprint $table) {
        $table->integer('temoignage_id')->unsigned()->index();
        $table->foreign('temoignage_id')->references('id')->on('temoignages')->onDelete('cascade');
        $table->integer('type_id')->unsigned()->index();
        $table->foreign('type_id')->references('id')->on('types')->onDelete('cascade');
        $table->primary(['temoignage_id', 'type_id']);
    });

These are my models :

Type

class Type extends Model {

    protected $guarded = [];

    public function temoignages()
    {
        return $this->belongsToMany('App\Temoignage');
    }
}

Temoignage

class Temoignage extends Model {

    protected $guarded = [];

    public function personne()
    {
        return $this->belongsTo('App\Personne');
    }

    public function types()
    {
        return $this->belongsToMany('App\Type');
    }
}

What I want to do, is to get in my edit function of TemoignagesController, all the Types associated. I tried many things like :

$temoignage->types()->get();

But I have an empty collection. Can someone can help or has already solve this problem ?

Thanks you :)

EDIT 1 : I followed this : http://ift.tt/1KOEout



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1M78EIk
via IFTTT

Aucun commentaire:

Enregistrer un commentaire