Names of database tables and columns
- netteman
- Member | 125
Hi
If I want to use something like this
$book->author->name
do I have to use the naming of database tables and columns used is this example https://doc.nette.org/…ase/explorer
https://files.nette.org/…chema-1-.png
I'm asking because if I tweaked the name of tables and columns I could use
$book->author
(this variable would be eg. 2) but
$book->author->name
gave me an error.
Thanks :)
- netteman
- Member | 125
The following code/database does not work
<?php
namespace App\Presenters;
use Nette;
use App\Model;
**Presenter**
class HomepagePresenter extends BasePresenter
{
private $database;
public function __construct(Nette\Database\Context $database)
{
$this->database = $database;
}//end mtd
public function renderDefault()
{
$this->template->books = $this->database->table("book");
}//end mtd
}//end class
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.