Reputation: 73
I have a problem that I couldn't deal with it. I have a News table includes TitleID, TextID, ImageID. And three more tables Titles, Texts, Images. I want to get all of them in one model. But when I try, got result like array in array . But I want it like:
[ News: [ { ID, Title, Text, Image } ] ]
Eloquent ORM responds it like:
[ News: [ { ID, Title: [ID, Title], Text: [ID, Text], Image: [ID, Image] } ] ]
Database Structure
News =>
+-----------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| TitleID | int(11) | NO | | NULL | |
| TextID | int(11) | NO | | NULL | |
| ImageID | int(11) | NO | | NULL | |
| CatID | int(11) | NO | | NULL | |
| OlusturmaZamani | datetime | NO | | NULL | |
| YayinZamani | datetime | NO | | NULL | |
| DuzenlemeZamani | datetime | YES | | NULL | |
| Onay | tinyint(11) | NO | | NULL | |
| Hit | int(11) | YES | | NULL | |
+-----------------+-------------+------+-----+---------+----------------+
Titles =>
+------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| TitleText | text | NO | | NULL | |
+------------+---------+------+-----+---------+----------------+
the other tables like title table.
Upvotes: 0
Views: 109
Reputation: 142208
Sounds like that ORM "over-normalizes". There is no reasonable reason for news attributes such as title, text, and image to be put in separate tables JOINed
by an "id".
"Eager loading" sounds like a kludge to make it feel like the columns are in the News
table when they aren't. This leads to unnecessary inefficiencies.
Upvotes: 0
Reputation: 673
Is there a reason you've extracted Title and Text to their own table?
A solution for you would be something like what you see in this post:
Add a custom attribute to a Laravel / Eloquent model on load?
Tweaked for your example:
Assume you changed the relationShip to "titleTable", just to avoid collision
class News extends Eloquent {
protected $appends = array('title');
public function getTitleAttribute()
{
return $this->titleTable->TitleText;
}
}
Upvotes: 1
Reputation: 755
Try eager loading.
If you have created relationships among News, Titles, Text and Image tables, you can load the relationship models by eager loading.
$news = News::with('title','text','image)->find(1);
Upvotes: 0