Laravel 4 - Can't retrieve data in a one-to-many relationship

前端 未结 5 1350
故里飘歌
故里飘歌 2021-01-21 18:45

I have a Quote model:

class Quote extends Eloquent {

    public function quote_lines() {
        return $this->hasMany(\'QuoteLine\');
    }    

}
         


        
5条回答
  •  抹茶落季
    2021-01-21 19:35

    The method name for a relationship MUST be in proper camel-case in order to use the magic property. E.g., In order to use, Quote::find($id)->quote_lines, the method must be named quoteLines()

    Allow me to explain:

    Calling Quote::find($id)->quote_lines; activates the magic __get method in the Eloquent class. __get() calls getAttribute($key) on the property being retrieved. So in this case, it calls getAttribute('quote_lines')

    If the key (quote_lines) is not available in the model's attributes array, it will instead search for a method in the class. It does this by transforming the key via camel_case(). Laravel's camel_case() method will transform quote_lines into quoteLines. It then looks for a function in your class named quoteLines(), and treats it as a relationship method if its found.

    Therefore, the relationship method MUST be written as quoteLines. (or any string that is proper camel case)

    public function quoteLines() {
      return $this->hasMany('QuoteLine');
    }    
    

    You may then access this relationship by using either Quote::find($id)->quote_lines or Quote::find($id)->quoteLines (both will work as both 'quote_lines' and 'quoteLines' evaluate to 'quoteLines' when camel-cased.)

    Footnote: "camel case" in laravel refers to a string of this form: heyThereWorld. The first letter must be lowercase, and the first letter of all subsequent words must be capitalized

提交回复
热议问题