草庐IT

php - Laravel 5 Eloquent 关系 : can't modify/overwrite relationship table property

coder 2024-04-06 原文

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

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

}

在我的 Controller 中,我使用 Laravel 的 with 方法从游览表中检索所有数据以及相关的类别数据:

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

一切正常。问题是我不想要当前原始形式的类别数据,我需要先重新排列它。但是,如果不先取消设置,我无法覆盖 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);
}

谁能解释一下这背后的逻辑?

最佳答案

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

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 取消设置关系

关于php - Laravel 5 Eloquent 关系 : can't modify/overwrite relationship table property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40908598/

有关php - Laravel 5 Eloquent 关系 : can't modify/overwrite relationship table property的更多相关文章

随机推荐