【问题标题】:Laravel HasMany Relation is returning all models, not related onesLaravel HasMany Relation 返回所有模型,而不是相关模型
【发布时间】: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


【解决方案1】:

如果你指定外键和本地键会怎样

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

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

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

你应该把它转换成整数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 2016-10-29
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多