【问题标题】:Laravel 4: Relation executing query using the wrong rowLaravel 4:使用错误行的关系执行查询
【发布时间】:2014-03-08 08:28:52
【问题描述】:

我有一个关系,我正试图开始工作,似乎是通过错误的列进行搜索。我有一个模型,用户词,它应该得到一个相关的词。我希望它使用 userword 表中的 word_id 列通过 word 表中的 id 搜索单词,但它似乎使用 userword 行的 id 来搜索单词。我想也许如果我告诉它在 hasOne() 的第三个参数中使用哪一列它会起作用,但无济于事。有问题的代码是:

public function word(){
    return $this->hasOne('Word', 'id', 'word_id');
}

任何帮助或想法将不胜感激!另外,如果您需要更多信息,请告诉我,我会在这里更新!非常感谢!

【问题讨论】:

    标签: laravel-4 eloquent


    【解决方案1】:

    您的父表是userword,相关的子表是word,在这种情况下,Userword 模型应该包含以下与word 表建立关系的方法:

    class Userwords {
    
        protected $table = 'userword';
    
        public function word(){
            return $this->hasOne('Word', 'userword_id'); // use the foreign key here
        }
    
    }
    

    在这种情况下,您的word 表应该包含userword_id 作为外键。所以,如果你有一个不同的外键定义词表,那么用那个外键代替userword_id

    另外请记住,表应该使用单词的复数名称,例如,words 应该是表名,但您使用了word,而Model 应该使用单数名称,例如,Word对于words 表,所以你在这里有一个不同的名称约定,所以在你的Word 模型中使用protected $table = 'word',在Userwords 模型中使用protected $table = 'userword'。所以,最后,它应该是这样的:

    class Userword {
    
        // change the table name in database (use userwords)
        protected $table = 'userwords';
    
        public function word(){
            return $this->hasOne('Word', 'userword_id'); // use the foreign key here
        }
    
    }
    

    对于words 表,应该是:

    class Word {
    
        // change the table name in database (use words)
        protected $table = 'words';
    
        public function userwords(){
            return $this->belongsTo('Userword');
        }
    
    }
    

    阅读手册了解更多关于Laravel Model Relationships的信息。

    【讨论】:

      猜你喜欢
      • 2017-01-14
      • 2014-08-19
      • 2013-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多