文章/分类–多对多
写在前面的话:在处理这个问题的时候心态已经爆炸了…在真正解决之后我们就来总结一下吧,毕竟以后要用到的…
项目环境:Laravel5.6+homestead+MySql
(下次用laravel6.0试一下,我们要跟上时代的步伐!!!!)
坚决介绍一下主要的功能吧。
文章管理:主要是牵扯到的文章的一系列属性和文章属于那几个分类,而且后面也会想到这个分类下有哪些文章;网上也有许多教程,Laravel的文档中也有提到…大家可以下先了解一下哦。
文章属性:标题(title)、内容(content)、发布时间(date)、状态(status)。(这里我已经将文章的属性简化了,其他的没有必要在这里废话。)
分类属性:分类名称(name)、分类别名(nick)、状态(status)。
(这里加上状态这个字段,方便以后的软删除)。
我们使用命令行建立两个表:文章表(articles)、分类表(sort)。
然后根据上面提到的属性添加字段:
$table->increments('id');
$table->string('title')->nullable()->comment('文章标题');
$table->text('content')->nullable()->comment('文章内容');
$table->string('img')->nullable()->comment('文章图片');
$table->string('auth')->nullable()->comment('文章发布者');
$table->string('date')->nullable()->comment('文章发布日期');
$table->string('mark')->nullable()->comment('文章摘要');
$table->string('keyword')->nullable()->comment('文章关键词');
$table->string('hot')->nullable()->comment('文章属性(推荐)');
$table->string('status')->nullable()->comment('文章状态');
$table->timestamps();
$table->increments('id');
$table->string('name')->nullable()->comment('分类名称');
$table->string('nick')->nullable()->comment('分类别名');
$table->string('img')->nullable()->comment('图片');
$table->string('status')->nullable()->comment('状态');
$table->string('mark')->nullable()->comment('摘要');
$table->timestamps();
请根据实际情况选择
既然多对多,我们就要将两个表关联起来。
中间表(article_sort):文章ID(article_id)、分类ID(sort_id)、状态(status)。
$table->increments('id');
$table->string('article_id')->nullable()->comment('文章ID');
$table->string('sort_id')->nullable()->comment('分类ID');
$table->string('status')->default(1)->comment('状态');
$table->timestamps();
建立这三个表的模型:
Article.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
//
protected $table = "articles";
protected $fillable = [
'title',
'content',
'img',
'date',
'mark',
'keyword',
'status'
];
public function sort()
{
# code...
return $this->belongsToMany('App\Models\Sort', 'article_sort', 'article_id', 'sort_id')->wherePivot('status', 1);
}
public function clearSort()
{
# code...
Article_Sort::clearSort($this->id);
}
}
Sort.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Sort extends Model
{
//
protected $table = "sort";
protected $fillable = [
'name',
'nick',
'img',
'status',
'mark',
];
public function articles()
{
# code...
return $this->hasMany('App\Models\Article');
}
}
Article_Sort.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Article_Sort extends Model
{
//
protected $table = 'article_sort';
protected $fillable = [
'article_id',
'sort_id',
'status'
];
public static function editThis($article_id,

本文介绍了在Laravel 5.6环境下,如何处理文章与分类的多对多关系,包括创建文章表、分类表、中间表以及相应的模型。文章属性包括标题、内容、发布时间和状态,分类属性包含名称、别名和状态。通过建立中间表`article_sort`连接文章和分类,并展示了部分控制器和表单代码。
最低0.47元/天 解锁文章
568

被折叠的 条评论
为什么被折叠?



