Example analysis of polymorphic Association usage of laravel 5.1 framework model

Time:2021-10-10

This paper illustrates the usage of polymorphic Association in laravel 5.1 framework model. Share with you for your reference, as follows:

What is polymorphic association? You can see from an example: for example, comments can belong to video or article. When there is a need to get video data from the comment table, polymorphic association is required.

A simple one sentence summary: one table corresponds to two tables.

1 realize polymorphic Association

1.1 structure of article table


  public function up()
  {
    Schema::create('articles', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->text('body');$table->timestamps();
    });
  }

1.2 video table structure


  public function up()
  {
    Schema::create('videos', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->text('description');
      $table->timestamps();
    });
  }

1.3 comment form structure


  public function up()
  {
    Schema::create('comments', function (Blueprint $table) {
      $table->increments('id');
      $table->text('content');
      $table->integer('item_id');
      $table->string('item_type');
      $table->timestamps();
    });
  }

↑ you need to specify Item here_ ID and item_ Type single introduction to item_ Type is mainly different from the table associated with it. Here, it has only two values: app \ article or app \ video.

1.4 writing polymorphic associations

Article and video:

public function comments()
  {
    /**
     *Second parameter: if your prefix is item_ Then write item. If it's something else, write something else.
     *The third parameter: item_ type
     *The fourth parameter: item_ id
     *The fifth parameter: the key associated with that table
     *(all but the second parameter above can be omitted)
     */
    return $this->morphMany(Comment::class, 'item', 'item_type', 'item_id', 'id');
  }

Comment:

public function video()
  {
    /**
     *All three parameters can be omitted, but K suggests you write them all
     */
    return $this->morphTo('item', 'item_type', 'item_id');
  }

use:


Route::get('/', function () {
  $video = App\Video::find(8);
  foreach ($video->comments as $comment) {
    echo $comment->id . ": " . $comment->item_type;
  }
});

For more information about laravel, readers who are interested can see the special topics on this site: introduction and advanced tutorial of laravel framework, summary of PHP excellent development framework, introduction to PHP object-oriented programming, introduction to PHP + MySQL database operation, and summary of common database operation skills for PHP

I hope this article will be helpful to your PHP Programming Based on laravel framework.