【发布时间】:2018-06-30 07:47:14
【问题描述】:
我正在使用 Laravel 5.5,我有一个电影模型:
class Movie extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
}
和一个评论模型:
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 个 cmets,其中 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->cmets 时,它会返回我所有的 4 个 cmets,而不仅仅是带有 movie_id tt3967856 的那两个。我该怎么办?
已解决: 我认为那是因为我对主键和外键使用了字符串类型。我将 ids 更改为整数(我的意思是 1,2,...而不是“tt3967856”等)并且一切正常:D
【问题讨论】:
-
你能显示
dd(Movie::with('comments')->find(1));的结果吗 -
它返回空值。我还尝试了 Movie::find(1) 并且它再次为空。
-
抱歉,请使用真实 ID
tt3967856而不是1。那么,dd(Movie::with('comments')->find('tt3967856'));显示了什么? -
显示此 ID + this 的电影信息:cmets: Illuminate\Database\Eloquent\Collection {#801 all: [],
-
奇怪了,我把ID改成整数而不是IMDb ID并迁移了,现在可以了。
标签: laravel laravel-5.5 laravel-eloquent