Laravel 5雄辩的关系:无法修改/覆盖关系表属性

Ini*_*igo 5 php

我正在使用Laravel 5的belongsToMany方法来使用中间数据透视表定义相关表。我的应用程序使用的是雄辩的模型TourTourCategory。在游览模型中,我有:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tour extends Model
{
    public function cats(){
        return $this->belongsToMany('App\TourCategory', 'tour_cat_assignments', 'tour_id', 'cat_id');
    }

}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我使用Laravel的with方法从巡回表中检索所有数据以及关联的类别数据:

$tours = Tour::with('cats')->get();
Run Code Online (Sandbox Code Playgroud)

一切正常。问题是我不希望类别数据具有其当前的原始格式,因此我需要先对其进行重新排列。但是,如果不cats先取消设置,就无法覆盖该属性:

public function serveTourData(){

    $tours = Tour::with('sections', 'cats')->get();

    foreach($tours as $tour){

        unset($tour->cats); // If I unset first, then it respects the new value. Why do I need to do this?

        $tour->cats = "SOME NEW VALUE";
    }

    Log::info($tours);
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释其背后的逻辑吗?

mck*_*yin 8

要覆盖某些模型上的关系,您可以使用:

public function serveTourData(){

$tours = Tour::with('sections', 'cats')->get();

foreach($tours as $tour){
    $tour->setRelation('cats', "SOME NEW VALUE");
}

Log::info($tours);
Run Code Online (Sandbox Code Playgroud)

}

对于 Laravel 5.4 - setRelation

当然如果你使用的是laravel >= 5.6,你可以通过unsetRelation来取消设置关系