簡體   English   中英

適用於數據庫模型的Laravel口才模型

[英]Laravel Eloquent Model adequate to Database Model

我對Web應用程序中的性能和代碼組織有疑問。 我有一個MySql DB表: 用戶 (id,un,pass), 作者 (id,簽名...), 讀者 (id,描述),其中user中的id列對應於這兩個表中的id。 該數據庫模型來自ER模型,其中用戶是這兩個模型的超類。 在我的應用程序中,我想從用戶那里得到作者讀者的數據,所以我的第一個問題是:我可以在Eloquent模型中進行某種繼承以平滑地做到這一點嗎?

我當前的設置是,我創建了兩個VIEW:authors(聯接userauthor )和readers( 聯接 user和reader ),我計划將它們與Eloquent中的WHERE子句一起使用。 這對性能不利嗎? 我知道MySql使用MERGE算法,因此這些查詢將在一個SQL命令中轉換,但是如果有人提出建議,什么是最好的方法,請回答。 謝謝!

您需要在兩個模型中都設置ER。

例如,在User.php模型中,您應該有一個稱為author()的方法。

class User extends Eloquent {

...

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

...

}

在您的Author.php模型中,您需要

class User extends Eloquent {

...

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

...

}

Reader.php模型也是如此。

您可以在docs頁面查看 ;)

如果一個字段可以鏈接到一個表,則可以使用多態關系。

多態關系

數據庫架構:

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');
    }
    ...
}

不過,我不確定這是最好的方法。

例如,您永遠無法確定$user->role->signature是否存在,您必須先檢查用戶是否是作者,否則可能會遇到意外錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM