Names of database tables and columns
- netteman
- Member | 129
The following code/database does not work
Template
{block content}
<h1 n:block=“title”>Books</h1>
{foreach $books as $book}
<div class=“book”>
<h2>{$book->title}</h2>
<div>{$book->author->name}</div>
</div>
{/foreach}
{/block}
Error
Trying to get property of non-object
<div><?php echo
Latte\Runtime\Filters::escapeHtml($book->author->name, ENT_NOQUOTES)
?></div>
-- Adminer 4.2.1 MySQL dump
SET NAMES utf8;
CREATE TABLE author
(
id_author
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(100) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (id_author
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE book
(
id
int(11) NOT NULL AUTO_INCREMENT,
author
int(11) NOT NULL,
title
varchar(100) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (id
),
KEY author
(author
),
CONSTRAINT book_ibfk_1
FOREIGN KEY (author
) REFERENCES
author
(id_author
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
If I change the database to this, everything works.
author.id_author → author.id
book.author → book.author_id
-- Adminer 4.2.1 MySQL dump
SET NAMES utf8;
CREATE TABLE author
(
id
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(100) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE book
(
id
int(11) NOT NULL AUTO_INCREMENT,
author_id
int(11) NOT NULL,
title
varchar(100) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (id
),
KEY author_id
(author_id
),
CONSTRAINT book_ibfk_1
FOREIGN KEY (author_id
)
REFERENCES author
(id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Do you need to know anything else?
Last edited by netteman (2016-04-29 20:13)
- David Matějka
- Moderator | 6445
This is expected behavior. If the column is named author
and you
use $book->author
then nette returns column value (id of an
author). You would have to use $book->ref('author')
which
returns referenced row.
However if the joining column is named author_id
(or e.g.
id_author
) and you use $book->author
then there is
no such column. So nette tries to find some association, which has a joining
column that contains given string. In this case, it finds author_id
and returns referenced row.