duandang2123 2018-10-08 15:04
浏览 16
已采纳

你如何在laravel雄辩中查询孩子和父母

I want to figure out how to query to get a result that was either created by the current user or the current users parent.

I have two tables users and workouts. Both tables have a created_by column, which stores the user id of whoever created said user or workout record.

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `created_by` int(10) unsigned DEFAULT NULL,
  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `users_created_by_foreign` (`created_by`),
  CONSTRAINT `users_created_by_foreign` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`)
);

CREATE TABLE `workouts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `created_by` int(10) unsigned NOT NULL,
  `description` text COLLATE utf8_unicode_ci,
  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `workouts_created_by_foreign` (`created_by`),
  CONSTRAINT `workouts_created_by_foreign` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`)
);

In my user model I have a function to return all the workouts that the user has created.

public function createdWorkouts(): HasMany
{
    return $this->hasMany(Workout::class, 'created_by');
}

What I want to figure out is, how can I query to find a workout using a ID but only for workouts the current user has created or the creator of the current user has created. Below is my current route logic, which only returns a workout created by the current user.

$user = User::find(1); // This would come from the JWT
if (!$workout = $user->createdWorkouts()->find($args[‘workout_id’])) {
    return $response->withJson([], 404);
}
  • 写回答

1条回答 默认 最新

  • dongxibeng5324 2018-10-08 15:31
    关注

    For this instance, I probably wouldn't use an eloquent relationship as it could be either the users id or their created_by value.

    Instead, I would change the method on your user model to read:

    public function createdWorkouts()
    {
        return Workout::where('created_by', $this->id)->orWhere('created_by', $this->created_by)->get();
    }
    

    Then you can do $user->createdWorkouts() which will return you a collection of all workouts where it was created by the user, or created by the user that created the user.

    As it is a collection, you then have access to all of the other methods on a collection such as find etc

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么