laravel - 检索多态关系 laravel 的所有者

标签 laravel eloquent polymorphism relationship

我正在尝试检索我在我的应用程序中定义的 Eloquent 多态关系的所有者。关系如下:Theme 可以由 EnseignantPartenaire 发布,因此两者都可以发布主题。下面是模型和对应的多态关系:

主题模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Theme extends Model
{

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

少校模型

<?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');
    }
}

我正尝试按照 doc 中显示的方式在我的 Blade View 中检索 theme 的所有者.

这是 Controller 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 Blade View

@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

<?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');
    }
}

注意:EnseignantPartenaire 继承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');
    }
}

学士

<?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_idthemePoster_type 是通过获取当前的EnseignantPartenaire id 和fonction 创建的。下面是负责获取这些属性的代码:

<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 table 的样本中看到的那样,它记录得很好,但我遇到了这个 {{ $theme->themePoster }} 的问题,它在这里不返回任何内容。

最佳答案

docs 中所述我们(默认情况下)需要以下内容:

  • 适当的数据库列。
  • 正确的关系声明。

在您的情况下,这将是以下内容:

// 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();
}

( Source ) 的 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 抛出异常,但我可能错了。

简而言之,我认为带有 Auth::guard('web')->user()->fonctioninput 发送了不正确的值。在您的情况下,它应该是 App\PartenaireApp\Enseignant

Laravel provides将某些字符串映射到正确类的解决方案。如果我陈述的问题是正确的,这将是一个很好的解决方案。您可以将键映射到正确的类。这将导致:

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

关于laravel - 检索多态关系 laravel 的所有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56875936/

相关文章:

laravel - 在不使用查询的情况下启动查询生成器

javascript - Vue JS,如何使 axios 请求 API 在加载 HTML DOM 组件之前首先运行?

javascript - Laravel 5如何通过下拉选择显示、隐藏div

mysql - 如何对可以具有 1-M 个多个实体的实体建模?

c++ - 选择正确的子类以编程方式实例化

laravel - Eloquent ORM中的自然订单,Laravel 4

javascript - 如何在 Vue 中同时绑定(bind)和发出数据?

laravel - 更改用于保存时间戳的列名称

c++ - C++ 17中的泛型工厂机制

python - 如何创建从外部库中的 sqlalchemy 模型继承的自定义类