gpt4 book ai didi

Laravel HasMany Relation 返回所有模型,而不是相关模型

转载 作者:行者123 更新时间:2023-12-01 05:57:33 24 4
gpt4 key购买 nike

我正在使用 Laravel 5.5,我有一个 Movie 模型:

  
class Movie extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
}

and a Comment model:

class Comment extends Model
{
public function movie(){
return $this->belongsTo(Movie::class);
}
}

我有一个电影实例(存储在 $movie 变量中):

id: "tt5726616",
title: "Call Me by Your Name",
original_title: "Call Me by Your Name",
rate: 4,
year: 2017,
length: "132",
language: "English, Italian, French, German",
country: "Italy, France, Brazil, USA",
director: "Luca Guadagnino",
created_at: "2018-01-21 15:28:31",
updated_at: "2018-01-21 15:28:31",

我有 4 条评论,其中 2 条与相应的电影相关:

all: [
App\Comment {#788
id: 1,
movie_id: "tt3967856",
author: "user1",
comment: "cool!",
rate: 2,
created_at: "2018-01-21 15:28:32",
updated_at: "2018-01-21 15:28:32",
},
App\Comment {#786
id: 2,
movie_id: "tt3967856",
author: "user2",
comment: "not bad!",
rate: 3,
created_at: "2018-01-21 15:28:32",
updated_at: "2018-01-21 15:28:32",
},
App\Comment {#785
id: 3,
movie_id: "tt5726616",
author: "user1",
comment: "cool!",
rate: 4,
created_at: "2018-01-21 15:28:32",
updated_at: "2018-01-21 15:28:32",
},
App\Comment {#784
id: 4,
movie_id: "tt5726616",
author: "user2",
comment: "not bad!",
rate: 5,
created_at: "2018-01-21 15:28:32",
updated_at: "2018-01-21 15:28:32",
},
],

问题是,当我调用 $movie->comments 时,它会返回我所有的 4 条评论,而不仅仅是那两 strip 有 movie_id tt3967856 的评论。我该怎么办?

已解决:我认为那是因为我在主键和外键中使用了字符串类型。我将 id 更改为整数(我的意思是 1,2,... 而不是“tt3967856”等)并且一切正常:D

最佳答案

如果指定外键和本地键怎么办

class Movie extends Model
{
protected $casts=['movie_id'=>'integer'];

public function comments(){
return $this->hasMany(Comment::class,movie_id,id);
}
}

更新:我还注意到 movie_id 在评论对象中有 string 类型

你应该把它转换成整数

关于Laravel HasMany Relation 返回所有模型,而不是相关模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48368711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com