Laravel HasMany正在返回所有模型,而不是相关模型
我使用的是Laravel 5.5,我有一个电影模型:Laravel HasMany正在返回所有模型,而不是相关模型,laravel,laravel-5.5,laravel-eloquent,Laravel,Laravel 5.5,Laravel Eloquent,我使用的是Laravel 5.5,我有一个电影模型: class Movie extends Model { public function comments(){ return $this->hasMany(Comment::class); } } 和评论模型: class Comment extends Model { public function movie(){ return
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变量中):
我有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条评论,而不仅仅是那两条带有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\u id
在comment对象中有字符串类型
您可以将其转换为整数您可以显示
dd(Movie::with('comments')->find(1))的结果吗代码>它返回null。我还尝试了Movie::find(1),但它再次为空。很抱歉,请使用真实IDtt3967856
而不是1
。那么,dd(Movie::with('comments')->find('tt3967856'))是什么代码>显示?它显示此ID的电影信息+此:注释:Illumb\Database\Eloquent\Collection{801 all:[],奇怪的是,我将ID更改为整数,而不是IMDb ID并迁移,现在一切正常。
class Movie extends Model
{
protected $casts=['movie_id'=>'integer'];
public function comments(){
return $this->hasMany(Comment::class,movie_id,id);
}
}