Skip to content
Advertisement

Laravel one-to-many relationship with different column than primary key

I have following two tables:

account:

+--------------------------+---------------------+------+-----+---------+-------+
| Field                    | Type                | Null | Key | Default | Extra |
+--------------------------+---------------------+------+-----+---------+-------+
| id                       | varchar(25)         | NO   | PRI |         |       |
| name                     | varchar(191)        | NO   | UNI | NULL    |       |
| status                   | tinyint(3) unsigned | NO   |     | NULL    |       |
| active                   | tinyint(3) unsigned | NO   |     | NULL    |       |

project:
+-----------------------+------------------+------+-----+---------+----------------+
| Field                 | Type             | Null | Key | Default | Extra          |
+-----------------------+------------------+------+-----+---------+----------------+
| id                    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| client_code           | varchar(191)     | NO   |     | NULL    |                |
| tags                  | varchar(500)     | YES  |     | NULL    |                |
| project_id            | int(11)          | NO   |     | NULL    |                |
| file_name             | varchar(191)     | NO   |     | NULL    |                |
| total_records         | int(11)          | NO   |     | NULL    |                |

There’s a one-to-many relationship between account and projects.

Foreign key in projects table is named account_code instead of account_id.

The issue being project identifier column that is of significance is project_id rather than id in projects table.

Here’s my Account model:

public function projects() {
    return $this->hasMany('AppProject', 'account_code');
}

Project model:

public function account() {
    return $this->belongsTo('AppAccount', 'account_code', 'project_id');
}

I have a row in projects table as:

 id: 9
 account_code: 0011T00002K95MLQAZ
 tags: cpi|test|dmf
 project_id: 312
 file_name: conf_matrix_dev_1579064650.tsv
 total_records: 19

I tried retrieving account detail that project_id 312 belongs to.

$project = AppProject::where('project_id', 312)->get();
dd($project->account->name);

This throws exception:

Property [account] does not exist on this collection instance

and with this:

$project = AppProject::find(312);

this tried to look into by id field instead of project_id.

How can I solve this without having to write a query?

Advertisement

Answer

The problem here is that get is retrieving you a collection instead of an instance. You can use

$project = AppProject::where('project_id', 312)->first();

instead and that should do the trick.

Hope it helps. Some other solutions are exposed here: Property [title] does not exist on this collection instance

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement