mardi 9 octobre 2018

How to get Laravel set table to 'stick' for collection

We have a Laravel model and sometimes we want to get data from it's default table, but other times from a different table. It all works from a data perspective, but when the collection is returned from the alternate table, the 'table' attribute still references the original table (even though the data is from the other one as expected).

If we dd() getTable(), it is correct:

$model = COUNTRIES;
$table = "countires";
$org_id = 1;
$org_collection = $model->setTable('merge_' . $table)->get() 
  ->where('organization_id', $org_id)->keyBy('id');
dd($model->getTable()); // *** THIS SHOWS THE 2nd TABLE AS EXPECTED

dd() ouput:

"merge_countries"

But with the exact same code, if we dd() the result the table attribute in the collection is still the 1st one ('orgs') and not 'merge_orgs' as expected even though the data is correctly coming from the 'merge_orgs' table:

$model = COUNTRIES;
$table = "countires";
$org_id = 1;
$org_collection = $model->setTable('merge_' . $table)->get() 
  ->where('organization_id', $org_id)->keyBy('id');
dd($org_collection); // *** THIS SHOWS THE 1st TABLE EVEN THOUGH THE getTable() ABOVE DOES NOT

dd() output:

Collection {#297
  #items: array:1 [
    3 => Country {#295
      #connection: "common"
      #table: "countries" <---- WHY IS THIS NOT 'merge_countries'???
      #hidden: array:2 [
        0 => "created_at"
        1 => "updated_at"
      ]
      #appends: array:1 [
        0 => "level"
      ]
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [
        "id" => 3
        "organization_id" => 1
        "region_id" => 2
        "name" => "Southpark"
        "active" => 1
        "created_at" => "2018-06-21 14:05:36"
        "updated_at" => "2018-06-21 13:25:27"
      ]
      #original: array:7 [
        "id" => 3
        "organization_id" => 1
        "region_id" => 2
        "name" => "Southpark"
        "active" => 1
        "created_at" => "2018-06-21 14:05:36"
        "updated_at" => "2018-06-21 13:25:27"
      ]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #visible: []
      #fillable: []
      #guarded: array:1 [
         0 => "*"
      ]
    }
  ]
}

Any idea how to address this? We're not sure what else to even try at this point. Laravel if 5.6 if that matters.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire