简体   繁体   中英

Laravel Eloquent Model adequate to Database Model

I have a question regarding performance and code organization in my web application. I have a MySql DB tables: user (id, un, pass), author (id, signature...), reader (id, description), where id column in user correspondes the id's in those two tables. That DB model comes from ER model where user is a superclass of those two. In my app I want to get an author or reader along with the data from user , so my first question is: Can I make some kind of inheritance in Eloquent model to do this smoothely?

My current setup is that i created two VIEWs: authors (joins user and author ) and readers ( joins user and reader ) and I plan to use them with WHERE clauses in Eloquent. Is this bad for performance? I know that MySql uses MERGE algorythm, so those queries will be translated in one SQL command, but if anyone has a proposal what is the best way to do this, please answer. Thanks!

You need to set ER inside both models.

As example in your User.php model you should have a method called author()

class User extends Eloquent {

...

  // User has one Author
  public function author()
  {
    return $this->hasOne('Author');
  }

...

}

In your Author.php model you'll need to have

class User extends Eloquent {

...

  public function user()
  {
    return $this->belongsTo('User', 'id');
  }

...

}

The same for Reader.php model.

You might take a look on the docs page ;)

You can use polymorphic relations if a field can be linked to one table.

Polymorphic relationships

DB Schema :

user
    id - integer
    un - string
    pass - string
    role_id - integer  ; id of a row from either reader or author table
    role_type - string ; either reader or author

reader
    id - integer
    user_id - integer
    description - text

posts
    id - integer
    user_id - integer
    signature - string

User.php

class User extends Eloquent {
    public function role() {
        return $this->morphTo();
    }
    ...
}

Reader.php

class Reader extends Eloquent {
    public function users() {
        return $this->morphMany('User', 'role');
    }
    ...
}

Author.php

class Author extends Eloquent {
    public function users() {
        return $this->morphMany('User', 'role');
    }
    ...
}

I am not sure this is the best way to go, though.

For example, you can never be sure that $user->role->signature will exist, you have to check if the user is a author first, or you might end up with unexpected errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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