setModel vs AddColumn - foreign table values


#1

Hello, this my be easy, but I’ve been stuck on this for a while.

When creating a model and not defining the columns some of the columns which are model defined as HasOne display the names from linked tables.

So, in example we have car companies with id assgined:
ID. | Name

  1. VW
  2. Audi
  3. BMW
  4. PSA

And owners:
Owner Name | Car ID
Mark | 3
John | 1

Using grid and set model on owners without columns defined I get:
Mark | BMW
John | VW

But… once I define the setmodel($owners, null) and then add columns one by one I get:
Mark | 3
John | 1

Is there a way to use AddColumn to add the field with the associated forgein name ?

Thank you in advance.


#2

Can you define your columns in the setmodel() function, to display the foreign names as you want?


#3

I’m not sure how to do it - help please. :slight_smile:


#4

when you add column be sure to add column “car” and not “car_id”. They have identical caption, but are actually two different fields.


#5

Model definition Model_CarOwners
$this->addField('name', ['caption'=>'First name','required'=>true]);
$this->hasOne('car_id', new Model_CarBrands())->addTitle(['caption'=>'Brand']);

Model definition Model_CarBrands
$this->addField('name', ['caption'=>'Brand','required'=>true]);

So, for the model definition above - if I’d like to display list of all car owners with car brands and not ids?

What I mean is the “magic” addTitle in the module definition makes a trick, so using
$g->setModel(Model_CarOwners($db));
will display everything perfect, but…

$g->setModel(Model_CarOwners($db),[name,car_id]);

will display just the First name of owner and id (not the name of the brand).


#6

addTitle() creates a read-only field of ‘car’ (shortened by removing _id) inside your CarOwners model. It’s declared as expression / subselect for the CarBrand name and is displayed in the grid by default.

$g->setModel(Model_CarOwners($db), ['name','car']);

Field ‘car’ should be available to you.