Cakephp 4 Slug生成

chy5wohz  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(53)

我有一个问题。我正在根据他们官方网站上的指南在Cakephp中构建CMS。一切都很顺利,但我有一个问题。正如文章所述,没有生成服务。一切都是100%按照教程完成的。
你能猜到是什么引起的吗?
我把它放在ArticlesTable中,但它似乎不起作用。

<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Utility\Text;
use Cake\Event\EventInterface;

class ArticlesTable extends Table
{
    public function beforeSave($event, $entity, $options)
    {
        if ($entity->isNew() && !$entity->slug) {
            $sluggedTitle = Text::slug($entity->title);
            $entity->slug = substr($sluggedTitle, 0, 191);
        }
    }

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('articles');
        $this->setDisplayField('title');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Editions', [
            'foreignKey' => 'edition_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
            'joinType' => 'INNER',
        ]);
        $this->hasMany('ArticlesComments', [
            'foreignKey' => 'article_id',
        ]);
        $this->hasMany('ArticlesGalleries', [
            'foreignKey' => 'article_id',
        ]);

    }

字符串
有什么想法吗?

vjhs03f7

vjhs03f71#

1.确保将其添加到ArticlesTable.php(src/Model/Table/ArticlesTable.php
1.确保您已添加以下use语句:

use Cake\ORM\Table;
use Cake\Utility\Text;
use Cake\Event\EventInterface;

字符串
我只能让它按照这个确切的顺序工作,如果use语句的顺序不同,我的语句不会生成slug。
完整代码:

<?php
// src/Model/Table/ArticlesTable.php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Utility\Text;
use Cake\Event\EventInterface;

class ArticlesTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);
        $this->addBehavior('Timestamp'); // automatically adds created and modified columns
    }

    public function beforeSave(EventInterface $event, $entity, $options)
    {
        if($entity->isNew() && !$entity->slug)
        {
            $sluggedTitle = Text::slug($entity->title);
            //trim slug to max. length
            $entity->slug = substr($sluggedTitle, 0, 191);
        }
    }
}

?>


这是特定于CakePHPCookbook(2023年11月24日发布)5.x的第56页,因此稍后可能不准确。

相关问题