Получить владельца полиморфных отношений Laravel - PullRequest
0 голосов
/ 03 июля 2019

Я пытаюсь найти владельца полиморфных отношений Eloquent, которые я определил в своем приложении.Вот соотношение: Theme может быть опубликовано либо Enseignant, либо Partenaire, поэтому оба могут публиковать темы.Вот модели и соответствующие полиморфные отношения:

Theme модель

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Theme extends Model
{

    public function themePoster(){
        return $this->morphTo();
    }
}

Enseignant модель

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Enseignant extends Model
{


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

    public function themes(){
        return $this->morphMany('App\Theme', 'themePoster');
    }
}

Partenaire модель

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Partenaire extends Model
{


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

    public function themes(){
        return $this->morphMany('App\Theme', 'themePoster');
    }
}

Я пытаюсь найти владельца theme в моем виде лезвия, как показано в doc .

Вот функция контроллера show:

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $theme = Theme::findOrFail($id);
        return view('themeShow', ['theme' => $theme]);
    }

themeShow представление лезвия

@extends('layouts.layout')

@section('content')
<body>
{{$theme->intitule}} <br>
{{$theme->categorie}} <br>
{{$theme->filiereDesiree}} <br>
{{$theme->description}} <br>
<a href=" {{url('themes')}} "><button>Voir tous</button></a>
@if(Auth::guard('web')->user()->hasRole('etudiant'))
<a href=""><button>Choisir thématique</button></a>
Proposé par {{ $theme->themePoster }}
@elseif(Auth::guard('web')->user()->id == $theme->themePoster_id)
<a href=" {{ url('themes/' .$theme->id. '/edit' ) }} "><button>Modifier thématique</button></a>
<form method="POST" action=" {{ route('themes.destroy', $theme->id ) }} ">
    @csrf
    @method('DELETE')
<a class="btn btn-danger"> <input  class="delete" type="submit" name="submit" value="Supprimer thématique"><i class="fa fa-trash"></i></a>
</form>
@endif
@jquery
<script type="text/javascript">
    $("input[type=submit]").on("click", function(){
        return confirm('Etes-vous sûr de vouloir de supprimer cette thématique?');
    });
</script>
</body>
@endsection

Так вот строка, предназначенная для получения владельцатема:

Proposé par {{ $theme->themePoster }}

Пока я ничего не получаю: Proposé par: ничего не возвращается.Что мне там не хватает ..?Я довольно новичок в Laravel, потому что это мое первое приложение и я впервые использую полиморфные отношения.Ваша помощь будет очень кстати

Редактировать

Поскольку эта информация может быть полезна для большего понимания .. вот моя структура базы данных:

Utilisateurs table

<?php

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

class CreateUtilisateursTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('utilisateurs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('nom');
            $table->string('prenom');
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->string('password');
            $table->string('fonction');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Примечание: Enseignant и Partenaire наследует Utilisateur.

Utilisateur модель

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Utilisateur extends Authenticatable
{
    use Notifiable;

    protected $table = 'utilisateurs';

    public function hasRole($role){
        return $this->fonction == $role;
    }

    public function etudiants(){
        return $this->hasMany('App\Etudiant');
    }

    public function enseignants(){
        return $this->hasMany('App\Enseignant');
    }

    public function partenaires(){
        return $this->hasMany('App\Partenaire');
    }
}

Enseignants таблица

<?php

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

class CreateEnseignantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('enseignants', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('utilisateur_id')->unique();
            $table->string('isAdmin');
            $table->string('nomEntreprise')->nullable();
            $table->string('descEntreprise')->nullable();
            $table->timestamps();
        });
    }

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

Partenaires таблица

<?php

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

class CreatePartenairesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('partenaires', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('utilisateur_id')->unique();
            $table->string('structure');
            $table->string('description_structure');
            $table->timestamps();
        });
    }

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

В основном themePoster_id и themePoster_type создаются путем получения текущего идентификатора Enseignant или Partenaire и функции.Вот код, отвечающий за получение этих атрибутов:

<input type="hidden" id="themePoster_id" name="themePoster_id" value= "{{Auth::guard('web')->user()->id}}">
<input type="hidden" id="themePoster_type" name="themePoster_type" value= "{{Auth::guard('web')->user()->fonction}}">

, и как вы можете видеть здесь в этом примере таблицы тем , он хорошо записан, но у меня возникают проблемы с этим {{ $theme->themePoster }}, который здесь ничего не возвращает.

1 Ответ

0 голосов
/ 05 июля 2019

Как указано в документах , нам (по умолчанию) необходимо следующее:

  • Правильные столбцы базы данных.
  • Правильные объявления отношений.

В вашем случае это будет следующим:

// Themes table:
$table->morphs('themePoster');

// Which is short for:
$table->string('themePoster_type');
$table->unsignedBigInteger('themePoster_id');


// Partenaire and Enseignant models:
public function themes()
{
    return $this->morphMany('App\Theme', 'themePoster');
}

// Theme model:
public function themePoster(){
    return $this->morphTo();
}

( Источник ) из morphs.

Соотношение полиморфной модели можетсделать это следующим образом:

$partenaire->themes()->create([
    ...
]);

// The default behavior will result in this theme db record:
 themePoster_type | themePoster_id | more columns here 
 -----------------|----------------|-------------------
 'App\Partenaire' | 1              | ...

Часть, где я думаю, что в вашем коде идет не так, будет значением themePoster_type.Предполагается, что ваша запись будет выглядеть следующим образом:

themePoster_type | themePoster_id | more columns here 
 -----------------|----------------|-------------------
 'partenaire'     | 1              | ...

Laravel не может найти partenaire в качестве модели, поэтому он не знает, в какую таблицу он должен смотреть.Я предполагаю, что Laravel выдает исключение, но я могу ошибаться.

Короче говоря, я думаю, что input с Auth::guard('web')->user()->fonction отправляет неправильное значение.В вашем случае это должно быть App\Partenaire или App\Enseignant.

Laravel предоставляет решение для сопоставления определенных строк с правильными классами.Это было бы хорошим решением, если бы проблема, о которой я говорю, была правильной.Вы можете сопоставить ключи с правильными классами.Это приведет к:

// AppServiceProvider@boot
Relation::morphMap([
    'partenaire' => 'App\Partenaire',
    'enseignant' => 'App\Enseignant',
]);
...