【问题标题】:Attach relation data directly to model将关系数据直接附加到模型
【发布时间】:2019-11-23 05:07:00
【问题描述】:

文章模型

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) 是否可以仅使用模型类来定义它,或者我需要将它映射到控制器中?

【问题讨论】:

  • 你可以使用eager loading', in controller write this $article->load('category');` 然后分类关系附加到你的文章集合中。

标签: laravel orm eloquent relationship


【解决方案1】:

您可以将自定义属性分配给您的模型类。但是您不能使用与您的 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

【讨论】:

    【解决方案2】:

    您可以使用appends,如@matticustard 所述,或者在检索模型时仅使用->with() 方法:

    $article = Articles::find($id)->with('category');
    

    然后,您可以通过以下方式访问类别名称:

    $categoryName = $article->category->name;
    

    希望对你有帮助。

    【讨论】:

    • 他说他不喜欢以$article->category->name 访问名称。他希望在article 对象中直接拥有name 属性。
    猜你喜欢
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多