文章对应分类多个
This commit is contained in:
@@ -4,11 +4,12 @@ namespace App\Models;
|
||||
|
||||
use App\Models\Traits\BelongsToCategory;
|
||||
use App\Models\Traits\HasOneCover;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class Article extends Model
|
||||
{
|
||||
|
||||
use HasOneCover, BelongsToCategory;
|
||||
use HasOneCover;
|
||||
|
||||
/**
|
||||
* 应进行类型转换的属性
|
||||
@@ -23,4 +24,35 @@ class Article extends Model
|
||||
return route('article.show', $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notes: 关联分类
|
||||
* @Author: 玄尘
|
||||
* @Date : 2021/4/2 9:11
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
|
||||
*/
|
||||
public function categories(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Category::class)
|
||||
->using(ArticleCategory::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notes: description
|
||||
* @Author: 玄尘
|
||||
* @Date : 2021/4/2 9:17
|
||||
* @param $query
|
||||
* @param $ids
|
||||
* @return mixed
|
||||
*/
|
||||
public function scopeByCategory($query, $ids)
|
||||
{
|
||||
if (!is_array($ids)) {
|
||||
$ids = [$ids];
|
||||
}
|
||||
|
||||
return $query->whereHas('categories', function ($q) use ($ids) {
|
||||
$q->whereIN('id', $ids);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
11
app/Models/ArticleCategory.php
Normal file
11
app/Models/ArticleCategory.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\Pivot;
|
||||
|
||||
class ArticleCategory extends Pivot
|
||||
{
|
||||
|
||||
//
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Models;
|
||||
|
||||
use Encore\Admin\Traits\AdminBuilder;
|
||||
use Encore\Admin\Traits\ModelTree;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class Category extends Model
|
||||
{
|
||||
@@ -36,7 +37,7 @@ class Category extends Model
|
||||
return $this->belongsTo(Article::class);
|
||||
break;
|
||||
case self::TYPE_ARTICLE:
|
||||
return $this->hasMany(Article::class);
|
||||
return $this->belongsToMany(Article::class);
|
||||
break;
|
||||
case self::TYPE_ADVERT:
|
||||
return $this->hasMany(Advert::class);
|
||||
@@ -60,6 +61,11 @@ class Category extends Model
|
||||
{
|
||||
return $this->belongsTo(Article::class);
|
||||
}
|
||||
|
||||
public function articles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Article::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notes: 获取当前分类及子分类ID
|
||||
|
||||
Reference in New Issue
Block a user