【问题标题】:Laravel can't access pivot additional column from pivot model itselfLaravel 无法从枢轴模型本身访问枢轴附加列
【发布时间】:2018-02-26 12:54:02
【问题描述】:

我有一个名为 UserTask 的数据透视模型,其中有一个访问器函数:

class UserTask extends Pivot implements HasMedia
{
    use HasMediaTrait;

    public function getCompletedAttribute()
    {
        return $this->getMedia()->isEmpty() && $this->completed;
    }



    public function task()
    {
        return $this->belongsTo(Task::class);
    }

}

我在我的Task 模型中这样指定关系:

class Task extends Model
{

    public function users()
    {
        return $this->belongsToMany(User::class, 'user_task')->using('App\Models\UserTask')->withPivot('completed');
    }
}

我收到以下错误:

"message": "未定义属性:App\Models\UserTask::$completed",

有人知道为什么会这样吗?

【问题讨论】:

  • 你在哪里看到这个错误?!
  • 它抛出一个异常。我正在从邮递员那里进行 API 调用。
  • 你的控制器是什么?

标签: php laravel model pivot laravel-5.5


【解决方案1】:

试试这个访问器函数:

public function getCompletedAttribute($value)
{
    return $this->getMedia()->isEmpty() && $value;
}

【讨论】:

  • 这会导致以下错误:Call to undefined method Illuminate\\Database\\Query\\Builder::fromRawAttributes()
  • 实际上这行得通.. 首先它不起作用,因为我将extends Pivot 更改为extends Model 只是为了测试它并忘记将其更改回来。奇怪,$value 是从哪里来的?
  • getCompletedAttribute($value)一起工作?
  • 来自文档:The original value of the column is passed to the accessor, allowing you to manipulate and return the value.
  • 您能给我发一份该文档的链接吗?我花了很长时间寻找。
猜你喜欢
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
相关资源
最近更新 更多