我正在使用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条评论,其中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->评论时,它会返回我的所有4条评论,而不仅仅是那些带有movie_id tt3967856的评论。我该怎么办?
解决: 我认为这是因为我使用字符串类型作为我的主键和外键。我将ids更改为整数(我的意思是1,2,...而不是“tt3967856”等),一切正常:D
答案 0 :(得分:0)
如果指定外键和本地键
,该怎么办?class Movie extends Model
{
protected $casts=['movie_id'=>'integer'];
public function comments(){
return $this->hasMany(Comment::class,movie_id,id);
}
}
<强>更新强>:
我还注意到movie_id
在评论对象
你应该把它强制转换为整数