mysql多态关联_Laravel5.1 框架模型多态关联用法实例分析

本文实例讲述了Laravel5.1 框架模型多态关联用法。分享给大家供大家参考,具体如下:

什么是多态关联? 一个例子你就明白了:好比如说评论 它可以属于视频类 也可以属于文章类,当有个需求是 从评论表中取到视频类的数据,这就需要用到多态关联了。

简单的一句话总结:一张表对应两张表。

1 实现多态关联

1.1 文章表的结构

public function up()

{

Schema::create('articles', function (Blueprint $table) {

$table->increments('id');

$table->string('title');

$table->text('body');$table->timestamps();

});

}

1.2 视频表结构

public function up()

{

Schema::create('videos', function (Blueprint $table) {

$table->increments('id');

$table->string('title');

$table->text('description');

$table->timestamps();

});

}

1.3 评论表结构

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。

1.4 编写多态关联

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框架的PHP程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值