首頁  >  文章  >  php框架  >  Laravel模型間關係設定分錶法詳解

Laravel模型間關係設定分錶法詳解

藏色散人
藏色散人轉載
2020-04-10 13:23:323051瀏覽

Laravel模型間關係設定分錶法詳解

在實際開發中常用到分庫分錶,例如使用者表分成100 張,那麼這個時候查詢資料需要設定分錶,例如Laravel 的Model 類別中提供了setTable方法:

推薦教學:《laravel教學

/**
 * Set the table associated with the model.
 *
 * @param  string  $table
 * @return $this
 */
public function setTable($table)
{
    $this->table = $table;
 
    return $this;
}

那麼資料表的增刪改查需要先new 一個模型實例,再設定表名。如:

(new Circle())->setTable("t_group_" . hashID($userid, 20))
->newQuery()
->where('group_id', $request->group_id)
->update($attributes);

這個很簡單,那麼在模型間關係例如 HasOne,HasMany 等使用這種方式的情況下,如何設定分錶呢?

找了半天沒找到好的方法,以HasOne 為例,只好複製Model 類別中的HasOne 方法,改成myHasOne,並傳入表名,並且在函數裡物件實例化後調用setTable,果然可以。

程式碼如下:

public function detail()
{
    return $this->myHasOne(Circle::class, 'group_id', 'group_id', 't_group_' . hashID($this->userid, 20));
}
 
public function myHasOne($related, $foreignKey = null, $localKey = null, $table)
{
    $foreignKey = $foreignKey ?: $this->getForeignKey();
 
    $instance = (new $related)->setTable($table);
 
    $localKey = $localKey ?: $this->getKeyName();
 
    return new HasOne($instance->newQuery(), $this, $instance->getTable() . '.' . $foreignKey, $localKey);
}

不知道大家有沒有更優雅的方式。

以上是Laravel模型間關係設定分錶法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除