数据透视表上的一对多关系

时间:2019-12-16 23:33:45

标签: laravel eloquent laravel-nova

我在数据库中已有数据,并且我想创建一对多关系。使用数据透视表时,如何限制或模拟一对多关系?

我想从数据透视表中获取数据,所以我认为可以这样做。

class Asset extends Model {
    public function publisher() {
        return $this->belongsTo(Publisher::class, 'asset_publisher');
    }
}

-

class Publisher extends Model {
    public function assets() {
        return $this->hasMany(Asset::class, 'asset_publisher');
    }
}

1 个答案:

答案 0 :(得分:0)

一种模拟一对多的可能方法是为数据透视表“ AssetPublisher”创建一个模型,这样您就可以拥有

dirs<-c("path/folder1","path/folder2")

for(dir in 1:length(dirs)){
  ##read in the list of files in each folder
  flist<-list.files(path=dirs[dir], pattern = "\\.csv$")

  data <- list()
  ## a second for loop to read thru what's inside each folder
  for (file in flist){message("working on", file) 
    indata<-read.csv(paste0(dirs[dir],"/",file))
    data<-rbind(data,indata)
    assign(paste0("data_",dir), data)
    }
}

您现在可以调用 class Publisher extends Model { public function assets() { return $this->belongsToMany(Asset::class, 'asset_publisher'); } } class AssetPublisher extends Model { public function publisher() { return $this->belongsTo(Publisher::class); } } class Asset extends Model { public function assetPublisher() { return $this->hasOne(AssetPublisher::class)->with('publisher'); } public function getPublisherAttribute(){ return $this->assetPublisher->publisher; } } 来获取Publisher实例,并调用$asset->publisher来获取所有资产实例