Laravel Eloquent分表方法并使用模型关联的实现(2)
3、好了,我们章节的分表模型已经完成了。那么如何使用模型关联呢?我们来看 Book 模型如何关联 Chapter
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Book extends Model
{
public function chapters ()
{
/*
* books表的id和chapters表中的book_id关联
* 一对多关系(一本书对应多条章节)
*/
$instance = new Chapter();
$instance->setSuffix($this->id % 10);
$foreignKey = $instance->getTable . '.' . $this->getForeignKey();
$localKey = $this->getKeyName();
return new HasMany($instance->newQuery(), $this, $foreignKey, $localKey);
}
}
到此 model 发表查询及 model 关联就完成了,如果有其他更好的方式,请大家不吝赐教。第一次发表文章,如有不对的地方希望大家多多指教!!也希望大家多多支持黑区网络。
