这篇文章主要给大家分享laravel框架多态关联的内容,很多新手不清楚什么是多态关联,下面就给大家介绍多态关联以及使用方法,感兴趣的朋友可以参考一下,希望大家阅读完这篇文章能有所收获。
什么是多态关联? 一个例子你就明白了:好比如说评论 它可以属于视频类 也可以属于文章类,当有个需求是 从评论表中取到视频类的数据,这就需要用到多态关联了。
简单的一句话总结:一张表对应两张表。
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');$table->timestamps();
});
}
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
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();
});
}
↑ 这里需要指定 item_id 和 item_type 单一介绍一下 item_type 它主要是区别关联于那张表的 我们这里它只有两个值:App\Article 或 App\Video。
Article 和 Video:
public function comments()
{
/**
* 第二个参数:如果你的前缀是item_ 那么就写item 如果是别的就写别的。
* 第三个参数:item_type
* 第四个参数:item_id
* 第五个参数:关联到那个表的键
* (以上除了第二个参数都可以省略)
*/
return $this->morphMany(Comment::class, 'item', 'item_type', 'item_id', 'id');
}
Comment:
public function video()
{
/**
* 三个参数都可以省略 不过K建议你还是写全
*/
return $this->morphTo('item', 'item_type', 'item_id');
}
使用:
Route::get('/', function () {
$video = App\Video::find(8);
foreach ($video->comments as $comment) {
echo $comment->id . ": " . $comment->item_type;
}
});
现在大家对于laravel多态关联是什么以及其用法应该都有所了解了吧,上述示例有一定的借鉴价值,有需要的朋友可以参考学习,想要了解更多laravel多态关联的内容,大家可以关注其他相关文章哦。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理