php – Laravel 5 Eloquent关系:无法修改/覆盖关系表属性

我使用Laravel 5的belongsToMany方法使用中间数据透视表定义相关表.我的应用程序是使用雄辩的模型Tour和TourCategory.在旅游模型中,我有

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');
    }

}

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

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

一切正常.问题是我不希望以当前原始形式的类别数据,我需要首先重新排列它.但是我不能在不首先取消它的情况下覆盖cat属性

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);
}

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

解决方法:

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

public function servetourData(){

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

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

Log::info($tours);

}

For laravel 5.4 – setRelation

当然,如果你使用laravel> = 5.6,你可以在unsetRelation之前取消关系

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...