【问题标题】:Indirect modification of overloaded on Laravel - RelationshipLaravel 上重载的间接修改 - 关系
【发布时间】:2020-07-23 10:56:11
【问题描述】:

我使用 Laravel 5,我有 2 个表:

  • “链接”表有 7 列,其中之一是“image_id”列。
  • “Image”表,在这个表中我有两列,一个“id”和“url”。

我想用单一的更新方法更新我的链接数据库以及相关的图片 url。

我试过这段代码:

public function update(Request $request, $id)
{
    // Validate the data
    $link = Link::find($id);

    $this->validate($request, array(
            'title' => 'required|max:255',
            'link'  => 'nullable',
            'description'  => 'required'
    ));
    

    $link = Link::find($id);

    $link->title = $request->input('title');
    $link->link = $request->input('link');
    $link->description = $request->input('description');
    $link->linkImage->url = 'testurl';

    $link->save();

    Session::flash('success', "Le lien à été correctement mis à jour.");

    return redirect()->route('links.index');
}

这是我的链接类:

<?php

namespace App\Models\Services;

use Illuminate\Database\Eloquent\Model;

class Link extends Model
{

/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'service_rubrique_link';

protected $fillable = ['title','description','ordre','image_id'];


public function linkImage() 
{
    return $this->belongsTo('App\Models\Storage\Imageup');
}

}

还有我的图像类:

<?php

namespace App\Models\Storage;

use Illuminate\Database\Eloquent\Model;

class Imageup extends Model
{

/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'image';

protected $fillable = ['id','url'];

public function servlinks() 
{
    return $this->hasMany('App\Models\Services\Link');
}

}

当我想保存时,我遇到了这个错误:

间接修改重载属性

App\Models\Services\Link::$linkImage 无效

你知道我的代码有什么问题吗?

谢谢。

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:

    正如消息所说,该属性是一个延迟加载的子模型。 更新没有意义...您应该将其用作方法(查询生成器)linkimage(),然后使用例如 ->update(['propertyname' => 'value'])

    见https://laravel.com/docs/7.x/eloquent-relationships#inserting-and-updating-related-models

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 1970-01-01
      • 2019-04-11
      • 2018-09-20
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      相关资源
      最近更新 更多