首页 > 解决方案 > 将关系数据直接附加到模型

问题描述

文章模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class Articles extends Model
{
    protected $table = 'articles';

    protected $primaryKey = 'idArticle';

    protected $fillable = [
        'idArticle', 'Topic', 'Image', 'Content', 'Views',
    ];

    protected $hidden = [
        'idCategory', 'idUser',
    ];

    public function category()
    {
        return $this->hasOne(Categories::class, 'idCategory', 'idCategory');
    }
}

所以现在当我打电话时$article = Articles::find(1);,它会从文章表中返回数据,当我添加时$article->category;,它会添加数据$article->category->Name。我想Name直接在里​​面$article- 像$article->category(所以$article->category->Name进入$article->category)是否可以仅使用模型类来定义它,或者我需要将它映射到控制器中?

标签: laravelormeloquentrelationship

解决方案


您可以将自定义属性分配给您的模型类。但是你不能使用与你的category()方法相同的属性名,因为它已经被$article->category.

一个例子给你一个名为category_name

class Articles extends Model
{
    // attributes to append to JSON responses
    protected $appends = ['category_name'];

    // ... your other properties and methods

    // your custom attribute
    public function getCategoryNameAttribute()
    {
        if (!is_null($this->category)) {
            return $this->category->Name;
        }

        return '';
    }
}

用于:

$article->category_name

推荐阅读