pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

<tfoot id='boA4u'></tfoot>
<legend id='boA4u'><style id='boA4u'><dir id='boA4u'><q id='boA4u'></q></dir></style></legend>
    1. <small id='boA4u'></small><noframes id='boA4u'>

        <bdo id='boA4u'></bdo><ul id='boA4u'></ul>

      <i id='boA4u'><tr id='boA4u'><dt id='boA4u'><q id='boA4u'><span id='boA4u'><b id='boA4u'><form id='boA4u'><ins id='boA4u'></ins><ul id='boA4u'></ul><sub id='boA4u'></sub></form><legend id='boA4u'></legend><bdo id='boA4u'><pre id='boA4u'><center id='boA4u'></center></pre></bdo></b><th id='boA4u'></th></span></q></dt></tr></i><div class="wiym2gg" id='boA4u'><tfoot id='boA4u'></tfoot><dl id='boA4u'><fieldset id='boA4u'></fieldset></dl></div>

      1. Laravel Eloquent:訪問屬性和動態(tài)表名

        Laravel Eloquent: Accessing properties and Dynamic Table Names(Laravel Eloquent:訪問屬性和動態(tài)表名)

      2. <small id='I0875'></small><noframes id='I0875'>

            • <tfoot id='I0875'></tfoot>
              <i id='I0875'><tr id='I0875'><dt id='I0875'><q id='I0875'><span id='I0875'><b id='I0875'><form id='I0875'><ins id='I0875'></ins><ul id='I0875'></ul><sub id='I0875'></sub></form><legend id='I0875'></legend><bdo id='I0875'><pre id='I0875'><center id='I0875'></center></pre></bdo></b><th id='I0875'></th></span></q></dt></tr></i><div class="agmkwsi" id='I0875'><tfoot id='I0875'></tfoot><dl id='I0875'><fieldset id='I0875'></fieldset></dl></div>

                <tbody id='I0875'></tbody>
                <bdo id='I0875'></bdo><ul id='I0875'></ul>
                <legend id='I0875'><style id='I0875'><dir id='I0875'><q id='I0875'></q></dir></style></legend>
                1. 本文介紹了Laravel Eloquent:訪問屬性和動態(tài)表名的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

                  問題描述

                  我正在使用 Laravel 框架,這個問題與在 Laravel 中使用 Eloquent 直接相關(guān).

                  I am using the Laravel Framework and this question is directly related to using Eloquent within Laravel.

                  我正在嘗試制作一個可在多個不同表中使用的 Eloquent 模型.這樣做的原因是我有多個基本相同但每年都不同的表,但我不想重復(fù)代碼來訪問這些不同的表.

                  I am trying to make an Eloquent model that can be used across the multiple different tables. The reason for this is that I have multiple tables that are essentially identical but vary from year to year, but I do not want to duplicate code to access these different tables.

                  • gamedata_2015_nations
                  • gamedata_2015_leagues
                  • gamedata_2015_teams
                  • gamedata_2015_players

                  我當然可以有一個帶有年份列的大表,但是每年有超過 350,000 行并且需要處理很多年,我決定將它們拆分為多個表會更好,而不是 4 個帶有額外表的大表每個請求的位置".

                  I could of course have one big table with a year column, but with over 350,000 rows each year and many years to deal with I decided it would be better to split them into multiple tables, rather than 4 huge tables with an extra 'where' on each request.

                  所以我想做的是為每個類創(chuàng)建一個類,并在 Repository 類中執(zhí)行類似的操作:

                  So what I want to do is have one class for each and do something like this within a Repository class:

                  public static function getTeam($year, $team_id)
                      {
                          $team = new Team;
                  
                          $team->setYear($year);
                  
                          return $team->find($team_id);
                      }
                  

                  我在 Laravel 論壇上使用了這個討論來讓我開始:http://laravel.io/forum/08-01-2014-defining-models-in-runtime

                  I have used this discussion on the Laravel forums to get me started: http://laravel.io/forum/08-01-2014-defining-models-in-runtime

                  到目前為止我有這個:

                  class Team extends IlluminateDatabaseEloquentModel {
                  
                      protected static $year;
                  
                      public function setYear($year)
                      {
                          static::$year= $year;
                      }
                  
                      public function getTable()
                      {
                          if(static::$year)
                          {
                              //Taken from https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L1875
                              $tableName = str_replace('\', '', snake_case(str_plural(class_basename($this))));
                  
                              return 'gamedata_'.static::$year.'_'.$tableName;
                          }
                  
                          return Parent::getTable();
                      }
                  }
                  

                  這似乎有效,但我擔心它沒有以正確的方式工作.

                  This seems to work, however i'm worried it's not working in the right way.

                  因為我使用的是 static 關(guān)鍵字,屬性 $year 保留在類中而不是每個單獨的對象中,所以每當我創(chuàng)建一個新對象時,它仍然根據(jù)上次設(shè)置的 $year 屬性保存在一個不同的對象.我寧愿 $year 與單個對象相關(guān)聯(lián),并且每次創(chuàng)建對象時都需要設(shè)置.

                  Because i'm using the static keyword the property $year is retained within the class rather than each individual object, so whenever I create a new object it still holds the $year property based on the last time it was set in a different object. I would rather $year was associated with a single object and needed to be set each time I created an object.

                  現(xiàn)在我試圖追蹤 Laravel 創(chuàng)建 Eloquent 模型的方式,但真的很難找到合適的地方來做到這一點.

                  Now I am trying to track the way that Laravel creates Eloquent models but really struggling to find the right place to do this.

                  例如,如果我將其更改為:

                  For instance if I change it to this:

                  class Team extends IlluminateDatabaseEloquentModel {
                  
                      public $year;
                  
                      public function setYear($year)
                      {
                          $this->year = $year;
                      }
                  
                      public function getTable()
                      {
                          if($this->year)
                          {
                              //Taken from https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L1875
                              $tableName = str_replace('\', '', snake_case(str_plural(class_basename($this))));
                  
                              return 'gamedata_'.$this->year.'_'.$tableName;
                          }
                  
                          return Parent::getTable();
                      }
                  }
                  

                  這在嘗試獲得單個團隊時效果很好.但是,對于關(guān)系,它不起作用.這是我在人際關(guān)系中嘗試過的:

                  This works just fine when trying to get a single Team. However with relationships it doesn't work. This is what i've tried with relationships:

                  public function players()
                  {
                      $playerModel = DataRepository::getPlayerModel(static::$year);
                  
                      return $this->hasMany($playerModel);
                  }
                  
                  //This is in the DataRepository class
                  public static function getPlayerModel($year)
                  {
                      $model = new Player;
                  
                      $model->setYear($year);
                  
                      return $model;
                  }
                  

                  如果我使用的是 static::$year,這同樣可以正常工作,但是如果我嘗試將其更改為使用 $this->year,那么這將停止工作.

                  Again this works absolutely fine if i'm using static::$year, but if I try and change it to use $this->year then this stops working.

                  實際的錯誤源于 $this->year 沒有在 getTable() 中設(shè)置,因此調(diào)用了父 getTable() 方法并返回了錯誤的表名.

                  The actual error stems from the fact that $this->year is not set within getTable() so that the parent getTable() method is called and the wrong table name returned.

                  我的下一步是嘗試弄清楚為什么它可以使用靜態(tài)屬性而不是非靜態(tài)屬性(不確定是否正確).我認為它只是在嘗試建立 Player 關(guān)系時使用 Team 類中的 static::$year .然而,這種情況并非如此.如果我嘗試強制出現(xiàn)這樣的錯誤:

                  My next step was to try and figure out why it was working with the static property but not with the nonstatic property (not sure on the right term for that). I assumed that it was simply using the static::$year from the Team class when trying to build the Player relationship. However this is not the case. If I try and force an error with something like this:

                  public function players()
                  {
                      //Note the hard coded 1800
                      //If it was simply using the old static::$year property then I would expect this still to work
                      $playerModel = DataRepository::getPlayerModel(1800);
                  
                      return $this->hasMany($playerModel);
                  }
                  

                  現(xiàn)在發(fā)生的情況是我收到一條錯誤消息,指出找不到 gamedata_1800_players.也許并不那么令人驚訝.但它排除了 Eloquent 只是使用 Team 類中的 static::$year 屬性的可能性,因為它清楚地設(shè)置了我發(fā)送到 getPlayerModel() 方法的自定義年份.

                  Now what happens is that I get an error saying gamedata_1800_players isn't found. Not that surprising perhaps. But it rules out the possibility that Eloquent is simply using the static::$year property from the Team class since it is clearly setting the custom year that i'm sending to the getPlayerModel() method.

                  所以現(xiàn)在我知道當 $year 在關(guān)系中設(shè)置并靜態(tài)設(shè)置時,getTable() 可以訪問它,但是如果它是非靜態(tài)設(shè)置的,那么它會在某處丟失并且對象不知道調(diào)用 getTable() 時關(guān)于此屬性的信息.

                  So now I know that when the $year is set within a relationship and is set statically then getTable() has access to it, but if it is set non-statically then it gets lost somewhere and the object doesn't know about this property by the time getTable() is called.

                  (注意在簡單地創(chuàng)建新對象和使用關(guān)系時它的工作意義不同)

                  (note the significance of it working different when simply creating a new object and when using relationships)

                  我意識到我現(xiàn)在已經(jīng)提供了很多細節(jié),所以為了簡化和澄清我的問題:

                  I realise i've given alot of detail now, so to simplify and clarify my question:

                  1) 為什么 static::$year 工作但 $this->year 不適用于關(guān)系,當兩者都在簡單地創(chuàng)建新對象時工作.

                  1) Why does static::$year work but $this->year not work for relationships, when both work when simply creating a new object.

                  2) 有沒有辦法可以使用非靜態(tài)屬性并實現(xiàn)我已經(jīng)使用靜態(tài)屬性實現(xiàn)的目標?

                  2) Is there a way that I can use a non static property and achieve what I am already achieving using a static property?

                  理由:即使在我完成一個對象并嘗試使用該類創(chuàng)建另一個對象后,靜態(tài)屬性仍將保留在類中,這似乎不正確.

                  Justification for this: The static property will stay with the class even after I have finished with one object and am trying to create another object with that class, which doesn't seem right.

                  示例:

                      //Get a League from the 2015 database
                      $leagueQuery = new League;
                  
                      $leagueQuery->setYear(2015);
                  
                      $league = $leagueQuery->find(11);
                  
                      //Get another league
                      //EEK! I still think i'm from 2015, even though nobodies told me that!
                      $league2 = League::find(12);
                  

                  這可能不是世界上最糟糕的事情,就像我說的,它實際上使用靜態(tài)屬性工作,沒有嚴重錯誤.然而,上面的代碼示例以這種方式工作是危險的,所以我想正確地做到這一點,避免這種危險.

                  This may not be the worst thing in the world, and like I said, it is actually working using the static properties with no critical errors. However it is dangerous for the above code sample to work in that way, so I would like to do it properly and avoid such a danger.

                  推薦答案

                  我假設(shè)你知道如何瀏覽 Laravel API/代碼庫,因為你需要它來完全理解這個答案......

                  I assume you know how to navigate the Laravel API / codebase since you will need it to fully understand this answer...

                  免責聲明:即使我測試了一些情況,我也不能保證它總是有效.如果您遇到問題,請告訴我,我會盡力幫助您.

                  Disclaimer: Even though I tested some cases I can't guarantee It always works. If you run into a problem, let me know and I'll try my best to help you.

                  我看到您有多種情況需要這種動態(tài)表名,所以我們將從創(chuàng)建一個 BaseModel 開始,這樣我們就不必重復(fù)自己了.

                  I see you have multiple cases where you need this kind of dynamic table name, so we will start off by creating a BaseModel so we don't have to repeat ourselves.

                  class BaseModel extends Eloquent {}
                  
                  class Team extends BaseModel {}
                  

                  到目前為止沒有什么令人興奮的.接下來我們看一下IlluminateDatabaseEloquentModel中的一個static函數(shù),編寫我們自己的靜態(tài)函數(shù),姑且稱之為year代碼>.(把這個放在BaseModel)

                  Nothing exciting so far. Next, we take a look at one of the static functions in IlluminateDatabaseEloquentModel and write our own static function, let's call it year. (Put this in the BaseModel)

                  public static function year($year){
                      $instance = new static;
                      return $instance->newQuery();
                  }
                  

                  這個函數(shù)現(xiàn)在除了創(chuàng)建當前模型的一個新實例,然后在它上面初始化查詢構(gòu)建器之外什么都不做.與 Laravel 在 Model 類中的做法類似.

                  This function now does nothing but create a new instance of the current model and then initialize the query builder on it. In a similar fashion to the way Laravel does it in the Model class.

                  下一步是創(chuàng)建一個函數(shù),在實例化模型上實際設(shè)置表.我們稱之為 setYear.我們還將添加一個實例變量來將年份與實際表名分開存儲.

                  The next step will be to create a function that actually sets the table on an instantiated model. Let's call this one setYear. And we'll also add an instance variable to store the year separately from the actual table name.

                  protected $year = null;
                  
                  public function setYear($year){
                      $this->year = $year;
                      if($year != null){
                          $this->table = 'gamedata_'.$year.'_'.$this->getTable(); // you could use the logic from your example as well, but getTable looks nicer
                      }
                  }
                  

                  現(xiàn)在我們必須改變year來實際調(diào)用setYear

                  Now we have to change the year to actually call setYear

                  public static function year($year){
                      $instance = new static;
                      $instance->setYear($year);
                      return $instance->newQuery();
                  }
                  

                  最后但并非最不重要的是,我們必須覆蓋 newInstance().例如,在使用 find() 時,此方法用于我的 Laravel.

                  And last but not least, we have to override newInstance(). This method is used my Laravel when using find() for example.

                  public function newInstance($attributes = array(), $exists = false)
                  {
                      $model = parent::newInstance($attributes, $exists);
                      $model->setYear($this->year);
                      return $model;
                  }
                  

                  這是基礎(chǔ)知識.使用方法如下:

                  That's the basics. Here's how to use it:

                  $team = Team::year(2015)->find(1);
                  
                  $newTeam = new Team();
                  $newTeam->setTable(2015);
                  $newTeam->property = 'value';
                  $newTeam->save();
                  

                  下一步是關(guān)系.這就是它變得非常棘手.

                  The next step are relationships. And that's were it gets real tricky.

                  關(guān)系的方法(如:hasMany('Player'))不支持傳入對象.他們接受一個類,然后從中創(chuàng)建一個實例.我能找到的最簡單的解決方案是手動創(chuàng)建關(guān)系對象.(在團隊中)

                  The methods for relations (like: hasMany('Player')) don't support passing in objects. They take a class and then create an instance from it. The simplest solution I could found, is by creating the relationship object manually. (in Team)

                  public function players(){
                      $instance = new Player();
                      $instance->setYear($this->year);
                  
                      $foreignKey = $instance->getTable.'.'.$this->getForeignKey();
                      $localKey = $this->getKeyName();
                  
                      return new HasMany($instance->newQuery(), $this, $foreignKey, $localKey);
                  }
                  

                  注意:外鍵仍將被稱為 team_id(沒有年份)我想這就是您想要的.

                  Note: the foreign key will still be called team_id (without the year) I suppose that is what you want.

                  不幸的是,您必須為您定義的每個關(guān)系執(zhí)行此操作.對于其他關(guān)系類型,請查看 IlluminateDatabaseEloquentModel 中的代碼.您基本上可以復(fù)制粘貼它并進行一些更改.如果您在 year-dependent 模型上使用大量關(guān)系,您還可以覆蓋 BaseModel 中的關(guān)系方法.

                  Unfortunately, you will have to do this for every relationship you define. For other relationship types look at the code in IlluminateDatabaseEloquentModel. You can basically copy paste it and make a few changes. If you use a lot of relationships on your year-dependent models you could also override the relationship methods in your BaseModel.

                  在 Pastebin

                  這篇關(guān)于Laravel Eloquent:訪問屬性和動態(tài)表名的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

                  【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

                  相關(guān)文檔推薦

                  Deadlock exception code for PHP, MySQL PDOException?(PHP、MySQL PDOException 的死鎖異常代碼?)
                  PHP PDO MySQL scrollable cursor doesn#39;t work(PHP PDO MySQL 可滾動游標不起作用)
                  PHP PDO ODBC connection(PHP PDO ODBC 連接)
                  Using PDO::FETCH_CLASS with Magic Methods(使用 PDO::FETCH_CLASS 和魔術(shù)方法)
                  php pdo get only one value from mysql; value that equals to variable(php pdo 只從 mysql 獲取一個值;等于變量的值)
                  MSSQL PDO could not find driver(MSSQL PDO 找不到驅(qū)動程序)

                  <small id='Kmjo8'></small><noframes id='Kmjo8'>

                  • <bdo id='Kmjo8'></bdo><ul id='Kmjo8'></ul>
                    <tfoot id='Kmjo8'></tfoot>

                      <legend id='Kmjo8'><style id='Kmjo8'><dir id='Kmjo8'><q id='Kmjo8'></q></dir></style></legend>
                            <tbody id='Kmjo8'></tbody>

                            <i id='Kmjo8'><tr id='Kmjo8'><dt id='Kmjo8'><q id='Kmjo8'><span id='Kmjo8'><b id='Kmjo8'><form id='Kmjo8'><ins id='Kmjo8'></ins><ul id='Kmjo8'></ul><sub id='Kmjo8'></sub></form><legend id='Kmjo8'></legend><bdo id='Kmjo8'><pre id='Kmjo8'><center id='Kmjo8'></center></pre></bdo></b><th id='Kmjo8'></th></span></q></dt></tr></i><div class="wkiiows" id='Kmjo8'><tfoot id='Kmjo8'></tfoot><dl id='Kmjo8'><fieldset id='Kmjo8'></fieldset></dl></div>
                          • 主站蜘蛛池模板: 工业冷却塔维修厂家_方形不锈钢工业凉水塔维修改造方案-广东康明节能空调有限公司 | STRO|DTRO-STRO反渗透膜(科普)_碟滤| 瓶盖扭矩测试仪-瓶盖扭力仪-全自动扭矩仪-济南三泉中石单品站 | 盘煤仪,盘料仪,盘点仪,堆料测量仪,便携式激光盘煤仪-中科航宇(北京)自动化工程技术有限公司 | 六维力传感器_六分量力传感器_模腔压力传感器-南京数智微传感科技有限公司 | 脉冲布袋除尘器_除尘布袋-泊头市净化除尘设备生产厂家 | 七维官网-水性工业漆_轨道交通涂料_钢结构漆 | 工业胀紧套_万向节联轴器_链条-规格齐全-型号选购-非标订做-厂家批发价格-上海乙谛精密机械有限公司 | 金属切削液-脱水防锈油-电火花机油-抗磨液压油-深圳市雨辰宏业科技发展有限公司 | 东莞画册设计_logo/vi设计_品牌包装设计 - 华略品牌设计公司 | 步进_伺服_行星减速机,微型直流电机,大功率直流电机-淄博冠意传动机械 | 【铜排折弯机,钢丝折弯成型机,汽车发泡钢丝折弯机,线材折弯机厂家,线材成型机,铁线折弯机】贝朗折弯机厂家_东莞市贝朗自动化设备有限公司 | 北京自然绿环境科技发展有限公司专业生产【洗车机_加油站洗车机-全自动洗车机】 | 低压载波电能表-单相导轨式电能表-华邦电力科技股份有限公司-智能物联网综合管理平台 | loft装修,上海嘉定酒店式公寓装修公司—曼城装饰 | 水压力传感器_数字压力传感器|佛山一众传感仪器有限公司|首页 | 华溶溶出仪-Memmert稳定箱-上海协烁仪器科技有限公司 | 搪玻璃冷凝器_厂家-越宏化工设备 | 西装定制/做厂家/公司_西装订做/制价格/费用-北京圣达信西装 | R507制冷剂,R22/R152a制冷剂厂家-浙江瀚凯制冷科技有限公司 | 二氧化碳/活性炭投加系统,次氯酸钠发生器,紫外线消毒设备|广州新奥 | 贵阳用友软件,贵州财务软件,贵阳ERP软件_贵州优智信息技术有限公司 | SOUNDWELL 编码器|电位器|旋转编码器|可调电位器|编码开关厂家-广东升威电子制品有限公司 | 发光字|标识设计|标牌制作|精神堡垒 - 江苏苏通广告有限公司 | 洗地机-全自动/手推式洗地机-扫地车厂家_扬子清洁设备 | 退火炉,燃气退火炉,燃气热处理炉生产厂家-丹阳市丰泰工业炉有限公司 | HYDAC过滤器,HYDAC滤芯,现货ATOS油泵,ATOS比例阀-东莞市广联自动化科技有限公司 | 防腐储罐_塑料储罐_PE储罐厂家_淄博富邦滚塑防腐设备科技有限公司 | 无负压供水设备,消防稳压供水设备-淄博创辉供水设备有限公司 | 电磁铁_小型推拉电磁铁_电磁阀厂家-深圳市宗泰电机有限公司 | 合肥注册公司|合肥代办营业执照、2024注册公司流程 | 老房子翻新装修,旧房墙面翻新,房屋防水补漏,厨房卫生间改造,室内装潢装修公司 - 一修房屋快修官网 | BESWICK球阀,BESWICK接头,BURKERT膜片阀,美国SEL继电器-东莞市广联自动化科技有限公司 | 尾轮组_头轮组_矿用刮板_厢式刮板机_铸石刮板机厂家-双驰机械 | 工业废水处理|污水处理厂|废水治理设备工程技术公司-苏州瑞美迪 今日娱乐圈——影视剧集_八卦娱乐_明星八卦_最新娱乐八卦新闻 | 轴流风机-鼓风机-离心风机-散热风扇-罩极电机,生产厂家-首肯电子 | CTAB,表面活性剂1631溴型(十六烷基三甲基溴化铵)-上海升纬化工原料有限公司 | 东莞工作服_东莞工作服定制_工衣订做_东莞厂服 | 北京银联移动POS机办理_收银POS机_智能pos机_刷卡机_收银系统_个人POS机-谷骐科技【官网】 | 垃圾清运公司_环卫保洁公司_市政道路保洁公司-华富环境 | 搪瓷反应釜厂家,淄博搪瓷反应釜-淄博卓耀 |