N
N
Nick Tit2015-11-26 16:25:26
Yii
Nick Tit, 2015-11-26 16:25:26

Advice on how best to form a model for the menu?

There is a table in the database

CREATE TABLE IF NOT EXISTS `pages` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `seo_keywords` varchar(255) NOT NULL,
  `seo_description` varchar(255) NOT NULL,
  `text` text NOT NULL,
  `slug` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;

INSERT INTO `pages` (`id`, `title`, `seo_keywords`, `seo_description`, `text`, `slug`) VALUES
(1, 'О магазине', 'ключевые_слова', 'описание', 'текст_страницы', 'about'),
(2, 'Оплата и доставка', 'ключевые_слова', 'описание', 'текст_страницы', 'buy_delivery'),
(3, 'Покупка в кредит', 'ключевые_слова', 'описание',  'текст_страницы', 'buy_credit'),
(4, 'Контакты', 'ключевые_слова', 'описание', 'текст_страницы', 'contacts');

It is necessary to display the menu in the layout
based on the data in this table
title - the name of the menu will be the
link to the page is formed - /page/ data_from_field_slug
in pure SQL would make a request
SELECT `title`, `slug` 
FROM pages

Does it make sense for my task to use ActiveRecord?
1) ActiveRecord
will return all fields of the pages table
$pages = Pages::find()
    ->asArray()
    ->all();

How to select only the required fields in ActiveRecord?
title, slug
2)
There is another option
$sql = 'SELECT `title`, `slug` FROM `pages`';
$pages = Yii::$app->db->createCommand($sql)->queryAll();

3)
There is another option
$pages = (new Query())
  ->from('pages')
  ->all();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
A1eksandr, 2015-11-26
@A1eksandr

As convenient and do it, in principle, any option is acceptable.
In terms of MVC and support, it's still better to use a model.

$pages = Pages::find()->asArray()
    ->all();

It's even better to use additional sets via class PagesQuery extends \yii\db\ActiveQuery
something like this
$pages = Pages::find()->forMenu()->asArray() 
    ->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question