简体   繁体   English

Laravel 4.2与自定义表名称的雄辩关系

[英]Laravel 4.2 Eloquent Relationship with custom table name

Im trying to access url property on files table by $post->file->url , but i'm getting "Trying to get property of non-object" error. 我试图通过$post->file->url访问文件表上的url属性,但出现“尝试获取非对象的属性”错误。 My table and model is different because i can't use File as model name. 我的表和模型不同,因为我不能使用File作为模型名称。 is there something missing? 缺少什么吗? I hope someone come with solution. 我希望有人提出解决方案。 here's my tables: 这是我的桌子:

- posts:
 [PK] id 
      title
 [FK] featured_image 

 - files:
 [PK] id                
      title
      url

my model: 我的模特:

class TheFile extends \Eloquent 
{
   protected $table = 'files';

   public function post() {
     return $this->belongsTo('Post');
   }
}


class Post extends \Eloquent 
{   
  protected $table = 'posts';

  public function file() {
    return $this->hasOne('TheFile', 'id', 'featured_image');   
  }
}

thanks in advance. 提前致谢。

Maybe I'm wrong but as I see it, you actually have the relationship the wrong way around here. 也许我错了,但正如我所见,您实际上在这里的关系是错误的。 If table X has one table Y then the FK field is on Y and related to the PK on X . 如果表X有一个表Y则FK字段在Y并且与X上的PK相关。 But you have it the other way around. 但是相反。

As such you need to do one of two things: 因此,您需要执行以下两项操作之一:

  1. Change your database to put post_id on files rather than having featured_image (points as file`.`id ) on posts 更改数据库以将post_id放在files而不是在posts上具有featured_image (指向files file`.`id点)

  2. Change your relationships to match your database structure: 更改关系以匹配数据库结构:

     class TheFile extends \\Eloquent { protected $table = 'files'; public function post() { return $this->hasOne('Post'); } } class Post extends \\Eloquent { protected $table = 'posts'; public function file() { return $this->belongsTo('TheFile'); } } 

    Obviously with your various field changes too if you aren't going to change the tables. 显然,如果您不打算更改表,那么各个字段也会发生变化。


The basic rule of thumb is that if a table has the FK it's the 'belongs to' table. 基本的经验法则是,如果表具有FK,则它是“属于”表。 The other table is either 'has one' or 'has many'. 另一个表是“有一个”或“有很多”。 The slight exception to this rule is obviously 'belongs to many' where a table can relate to another table where neither has an FK - but even that's a specialised version of the same rule - X 'has many' X_Ys and Y 'has many' X_Ys and X_Y belongs to X and X_Y belongs to Y . 该规则的轻微例外显然是“属于许多”,其中一个表可以与另一个都不具有FK的表相关-但这甚至是同一规则的专门版本X “有很多” X_YsY “有很多” X_YsX_Y属于XX_Y属于Y So it's just syntactic sugar really. 因此,它实际上只是语法糖。

I changed my table name to medias, and my model to Media. 我将表名更改为media,将模型更改为Media。 Then put these code into Post model . 然后将这些代码放入Post模型。 It's works. 其作品。 The name of tables, model and method must be similar. 表,模型和方法的名称必须相似。

public function media() {
    return $this->belongsTo('Media', 'featured_image', 'id');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM