【问题标题】:How to get property or method in relationship ( laravel - eloquent )如何在关系中获取属性或方法(laravel - eloquent)
【发布时间】:2020-01-18 07:22:50
【问题描述】:

在后期模型中

function user()
{
    return $this->belongsTo( \App\User::class);
}

在用户模型中

function posts()
{
    return $this->hasMany( \App\Post::class);
}


function somedata() 
{
    return  date('i') * 1000  + date('s'); 
}

在控制器中

$posts = Post::query()
        ->where('id', 10)
        ->with('user')
        ->get();

但它没有在用户模型中获得“某些数据”。

如何将这些数据与帖子一起拖动?

【问题讨论】:

  • 你试过$posts->first()->somedata();$posts 应该是 Collection 的对象。
  • 您的 $posts 是集合,因此您需要使用循环 $posts 作为 $post 并访问 $post->user->somedata 方法

标签: laravel eloquent orm


【解决方案1】:

尝试将其作为属性并将其附加到模型中
Post.php

/**
 * The accessors to append to the model's array form.
 *
 * @var array
 */
protected $appends = ['someData'];

/**
 * Get the some data for the post.
 *
 * @return int
 */
public function getSomeDataAttribute()
{
    return  date('i') * 1000  + date('s');
}

【讨论】:

  • 你太好了。谢谢 。我希望我能找到一些关于雄辩模型保留关键字的文档..
【解决方案2】:

你需要设置一个Accessor:

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class User extends Model
    {
        /**
         * Get the user's somedata.
         *
         * @return string
         */
        public function getSomedataAttribute()
        {
            return 'somedata';
        }
    }

另见:https://laravel.com/docs/5.8/eloquent-mutators

【讨论】:

  • 很好的开始@robert,但他也需要附加它。
  • 仅当我想将属性返回到 JSON 时,$append 不是吗?
  • @Robert-GabrielSTANCIU 所有 Eloquent 模型在响应返回时都会自动序列化为 JSON
  • 当然,但是如果他在 SPA 中使用响应,将“somedata”添加到 $appends 会有所帮助。即使他没有将'somedata'添加到$appends,他仍然可以访问$user->somedata
猜你喜欢
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多