douyu4822 2018-08-01 15:08
浏览 250

在Laravel构造函数中将模型链接到父级

Maybe I'm searching it all wrong but I haven't been able to figure out an answer.. Say I have a model Building, which always has n Floor(s)

I would like to write a constructor for Building, in which I could specify a number of Floor(s) to be created. The problem is that I can't link back a Floor to the Building because when the constructor for Building is being called, it doesn't have a primary key yet...

Basically, my code looks like this but doesn't work:

class Building extends Model {
  public function __construct($nbFloors) {
    for($i=0; $i<$nbFloors; $i++) {
       $foo = new Floor();
       $foo->building_id = $this->id;
       $foo->save();
    }
  }
}

What would be the correct solution to achieve something like that?

  • 写回答

3条回答 默认 最新

  • douda5706 2018-08-01 15:26
    关注

    The primary key will never be available in the constructor and your constructor's definition is not compatible with Model which expects an array of attributes as the first argument.

    You're performing too much logic in your constructor, a constructor is meant to just instantiate an object and its dependencies, not perform business logic. By doing this in your constructor, you're actually going to be attempting to create new floors EVERY time your Model is instantiated which includes when your model is retrieved from the database.

    I'd recommend adding a new method like:

    public function createWithFloors($n) {
        $this->save();
        ...
    }
    

    Now, you can use the model as it's expected and call the create method:

    $building = new Building(['name' => 'Empire State']);
    $building->createWithFloors(102);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀