Полиморфная ассоциация Laravel (морфология, морфмАния) В процессе разработки веб-сайта мы часто сталкиваемся с продуктами для комментариев, статьями для комментариев, магазинами комментариев и так далее. Когда мы сталкиваемся с такими потребностями, мы часто создаем новую форму комментариев. Затем мы используем поле типа, чтобы различать объект процесса разработки комментариев следующим образом:
Новая операция с таблицей
php artisan make:model Models/Comments -m
Поля таблицы:
public function up() { Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('member_id'); $table - > string ('comment_object_type'); comment object Table - > integer ('comment_object_id'); ID of comment object Table - > text ('comment_content'); comment content $table->tinyInteger('status'); }); }
Выполните миграцию данных:
php artisan migrate
Создавайте пользователей данных с идентификаторами 2 и 4, комментируйте товары с идентификаторами 1,2,3,4:
INSERT INTO `comments`(`member_id`,`comment_object_type`,`comment_object_id`,`status`,`created_at`,`updated_at`) VALUES (2,'App\Models\Goods',1,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'App\Models\Goods',2,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'App\Models\Goods',3,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'App\Models\Goods',4,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (4,'App\Models\Goods',3,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (3,'App\Models\Goods',4,0,'2018-09-07 15:58:04','2018-09-07 15:58:04')
2. Пользователи с идентификатором 2 прокомментировали магазины с идентификатором 1,4
INSERT INTO `comments`(`member_id`,`comment_object_type`,`comment_object_id`,`status`,`created_at`,`updated_at`) VALUES (2,'App\Models\Stores',1,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'), (2,'App\Models\Stores',4,0,'2018-09-07 15:58:04','2018-09-07 15:58:04'),
запрос После завершения обработки данных нам нужно выполнить запрос, запросить все отзывы с идентификатором товара 2 и запросить информацию рецензентов. Общие вопросы:
public function comment_list(Requset $request, Goods $goods) { # Query for all comments on merchandise $comments = Comment::where('comment_object_type',Goods::class)->where('comment_object_id',$goods->id)->get(); if($comments) { foreach($comments as $comment) { $comment->member = Member::find('id',$comment->member_id) } } dd($comments) }
Общая Проверка Совместной Таблицы
Comment.php файл
# Comment Model File Modification # Find information about users of reviews public function member() { return $this->belongsTo(Member::class, 'comment_member_id'); }
Запрос требований
public function comment_list(Requset $request, Goods $goods) { # Query for all comments on merchandise $comments = Comment::where('comment_object_type',Goods::class)->where('comment_object_id',$goods->id)->get(); # This eliminates the need for a loop to call $item - > member directly to view user information while the template is traversing dd($comments) }
Полиморфный запрос
Comment.php файл
# Comment Model File Modification # Comment Target public function comment_object() { return $this->morphTo(); } # Find information about users of reviews public function member() { return $this->belongsTo(Member::class, 'comment_member_id'); }
Goods.php файл
# Comments on commodity linkages public function comments() { return $this->morphMany(Comment::class,self::class,'comment_object_type','comment_object_id'); }
Запрос требований
public function comment_list(Requset $request, Goods $goods) { # Query for all comments on merchandise $comments =$goods->comments()->with('member')->paginate(15); dd($comments) }