cakephp 和 add 方法(外键)

发布于 2024-11-23 21:47:50 字数 3394 浏览 0 评论 0原文

刚开始使用 cakephp,几年后几乎使用 php 没有使用它......

我有一个像这样的表结构: 父表......客户:

<?php
class Cliente extends AppModel
{
    var $name = 'Cliente';
        var $validate = array(
                            'nombre' => array('rule'=>'notEmpty')
                             );
        var $hasMany = array(
            'Proyecto' => array(
                'className'  => 'Proyecto',
                'foreignKey' => 'cliente_id',
                'order'      => 'Proyecto.nombre ASC',
                'dependent'  => true                
            )
        );
}
?>

子表:Proyects.. 一个客户可以分配多个项目。

<?php
class Proyecto extends AppModel
{
    var $name = 'Proyecto';
        var $validate = array(
                            'nombre' => array('rule'=>'notEmpty')
                             );
        //var $belongsTo = 'Cliente';
        var $belongsTo = array(
            'Cliente' => array(
                'className' => 'Cliente',
                'foreignKey' => 'cliente_id'
            )
        );
}
?>

只能从索引客户端视图添加(INSERT)项目。所以,我有这个添加(anadir)方法:

    function anadir($cliente_id, $nombre) {
        if (!empty($this->data)) {
//                        echo "El código de cliente 22222: ". $this->data['Proyecto']['id'] . "</br>";
//                        echo "El código de cliente fk: ". $this->data['Proyecto']['cliente_id'] . "</br>" ;
//                        print_r($this->data);
                        //$this->data['Proyecto']['cliente_id'] = $cliente_id;
            if ($this->Proyecto->save($this->data)) {
                $this->Session->setFlash('El proyecto ha sido grabado.');
                $this->redirect(array('controller'=>'clientes', 'action'=>'listar'));
            }
                } else {  
                        //echo "El código de cliente 11111: ". $this->data['Proyecto']['id'];                  
                    $this->data['Proyecto']['cliente_id'] = $cliente_id; 
                }
                $this->set('idcliente', $cliente_id);
                $this->set('nombrecliente', $nombre);
    }

我可以在“anadir.ctp”视图中显示父客户端(id和编号),但它总是更新相同的项目,仅更改名称和描述。表中不执行 ADD/INSERT,仅执行 UPDATE。

<!-- File: /app/views/proyectos/anadir.ctp -->  

<h1>A&ntilde;adir proyecto a cliente <?php echo "[$idcliente] - $nombrecliente"; ?></h1>
<?php
    //echo $this->Form->create('Proyecto', array('action' => 'anadir'));
    echo $this->Form->create('Proyecto', array('url' => '/proyectos/anadir/'.$idcliente.'/'.$nombrecliente)); // array('action' => 'anadir'));
    echo $this->Form->input('cliente_id', array('type' => 'hidden'));
    echo $this->Form->input('nombre');
    echo $this->Form->input('descripcion', array('rows' => '10'));
    echo $this->Form->end('Grabar proyecto');
    echo $this->Html->link('Cancelar', array('controller'=>'clientes', 'action'=>'listar'));
?>

当然这是一个新手问题,但我几乎尝试了所有方法。

有什么想法吗?

提前致谢。

==== 最后====

经过几天的努力解决这个问题,它现在正在运行。但我无法理解这个问题,我也没有解释为什么我遇到了这个奇怪的问题...

所以我将期待 symfony2 也许更难开始,但我希望更灵活(具有多主键和外键支持,主要)并且比cakephp清晰。

just starting with cakephp and almost with php after a few years without use it....

I have a table structure like this:
Parent table...... Clients:

<?php
class Cliente extends AppModel
{
    var $name = 'Cliente';
        var $validate = array(
                            'nombre' => array('rule'=>'notEmpty')
                             );
        var $hasMany = array(
            'Proyecto' => array(
                'className'  => 'Proyecto',
                'foreignKey' => 'cliente_id',
                'order'      => 'Proyecto.nombre ASC',
                'dependent'  => true                
            )
        );
}
?>

And child table: Proyects..
A client can have several projects assigned.

<?php
class Proyecto extends AppModel
{
    var $name = 'Proyecto';
        var $validate = array(
                            'nombre' => array('rule'=>'notEmpty')
                             );
        //var $belongsTo = 'Cliente';
        var $belongsTo = array(
            'Cliente' => array(
                'className' => 'Cliente',
                'foreignKey' => 'cliente_id'
            )
        );
}
?>

Proyects only can be added (INSERT) from the index client view. So, I have this add (anadir) method:

    function anadir($cliente_id, $nombre) {
        if (!empty($this->data)) {
//                        echo "El código de cliente 22222: ". $this->data['Proyecto']['id'] . "</br>";
//                        echo "El código de cliente fk: ". $this->data['Proyecto']['cliente_id'] . "</br>" ;
//                        print_r($this->data);
                        //$this->data['Proyecto']['cliente_id'] = $cliente_id;
            if ($this->Proyecto->save($this->data)) {
                $this->Session->setFlash('El proyecto ha sido grabado.');
                $this->redirect(array('controller'=>'clientes', 'action'=>'listar'));
            }
                } else {  
                        //echo "El código de cliente 11111: ". $this->data['Proyecto']['id'];                  
                    $this->data['Proyecto']['cliente_id'] = $cliente_id; 
                }
                $this->set('idcliente', $cliente_id);
                $this->set('nombrecliente', $nombre);
    }

I can show the parent client (id and number) in the 'anadir.ctp' view, but it always update the same proyect, changing the name and description only. No ADD/INSERT is done in the table, only UPDATE.

<!-- File: /app/views/proyectos/anadir.ctp -->  

<h1>Añadir proyecto a cliente <?php echo "[$idcliente] - $nombrecliente"; ?></h1>
<?php
    //echo $this->Form->create('Proyecto', array('action' => 'anadir'));
    echo $this->Form->create('Proyecto', array('url' => '/proyectos/anadir/'.$idcliente.'/'.$nombrecliente)); // array('action' => 'anadir'));
    echo $this->Form->input('cliente_id', array('type' => 'hidden'));
    echo $this->Form->input('nombre');
    echo $this->Form->input('descripcion', array('rows' => '10'));
    echo $this->Form->end('Grabar proyecto');
    echo $this->Html->link('Cancelar', array('controller'=>'clientes', 'action'=>'listar'));
?>

Surely it is a newbie question but I have tried almost everything.

Any idea ?

Thanks in advance.

==== Finally ====

After a few days trying to solve this it is running now. But I cannot understand the problem and I have no explanation why I have had that weird problem...

So I am going to look forward symfony2 Perhaps more difficult to start with but I hope more flexible (with multi Primary Keys and foreign key support, mainly) and clear than cakephp.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

朦胧时间 2024-11-30 21:47:50

上面的模型是相同的

,但更改下面的代码并尝试

function anadir() {//add method has not neet parameters
    if (!empty($this->data)) {
       //                        echo "El código de cliente 22222: ". $this-      >data['Proyecto']['id'] . "</br>";
       //                        echo "El código de cliente fk: ". $this->data['Proyecto']['cliente_id'] . "</br>" ;
      //                        print_r($this->data);
                    //$this->data['Proyecto']['cliente_id'] = $cliente_id;
        if ($this->Proyecto->save($this->data)) {
            $this->Session->setFlash('El proyecto ha sido grabado.');
            $this->redirect(array('controller'=>'clientes', 'action'=>'listar'));
        }
            } else {  
                    //echo "El código de cliente 11111: ". $this->data['Proyecto']['id'];                  
                $this->data['Proyecto']['cliente_id'] = $cliente_id; 
            }
            $this->set('idcliente', $cliente_id);
            $this->set('nombrecliente', $nombre);
}

<!-- File: /app/views/proyectos/anadir.ctp -->  

<h1>Añadir proyecto a cliente <?php echo "[$idcliente] - $nombrecliente"; ?></h1>
 <?php
 echo $this->Form->create('Proyecto');

echo $this->Form->input('Proyecto.cliente_id', array('type' => 'hidden'));
echo $this->Form->input('Proyecto.nombre');
echo $this->Form->input('Proyecto.descripcion', array('rows' => '10'));
echo $this->Form->submit('Grabar proyecto',array('url'=> array('controller'=>'proyectos','action'=>'anadir'));
cho $this->Form->end();
echo $this->Html->link('Cancelar', array('controller'=>'clientes', 'action'=>'listar'));
?>

Above Model are same

but change below code and try

function anadir() {//add method has not neet parameters
    if (!empty($this->data)) {
       //                        echo "El código de cliente 22222: ". $this-      >data['Proyecto']['id'] . "</br>";
       //                        echo "El código de cliente fk: ". $this->data['Proyecto']['cliente_id'] . "</br>" ;
      //                        print_r($this->data);
                    //$this->data['Proyecto']['cliente_id'] = $cliente_id;
        if ($this->Proyecto->save($this->data)) {
            $this->Session->setFlash('El proyecto ha sido grabado.');
            $this->redirect(array('controller'=>'clientes', 'action'=>'listar'));
        }
            } else {  
                    //echo "El código de cliente 11111: ". $this->data['Proyecto']['id'];                  
                $this->data['Proyecto']['cliente_id'] = $cliente_id; 
            }
            $this->set('idcliente', $cliente_id);
            $this->set('nombrecliente', $nombre);
}

<!-- File: /app/views/proyectos/anadir.ctp -->  

<h1>Añadir proyecto a cliente <?php echo "[$idcliente] - $nombrecliente"; ?></h1>
 <?php
 echo $this->Form->create('Proyecto');

echo $this->Form->input('Proyecto.cliente_id', array('type' => 'hidden'));
echo $this->Form->input('Proyecto.nombre');
echo $this->Form->input('Proyecto.descripcion', array('rows' => '10'));
echo $this->Form->submit('Grabar proyecto',array('url'=> array('controller'=>'proyectos','action'=>'anadir'));
cho $this->Form->end();
echo $this->Html->link('Cancelar', array('controller'=>'clientes', 'action'=>'listar'));
?>
老街孤人 2024-11-30 21:47:50

因此,看起来(正如deizel建议的那样)您已经在$this->data中以某种方式设置了id,可能是一个字段表格有误,不确定(您可以在这里发布您的观点,以便我们查看)。检查它的最好方法是监视实际的 SQL 查询;将其放在 $this->Model->save() 之后(尚未添加 $this->Model->create(),用于调试目的) :

$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);

将上述输出添加到您的问题中。

关于 $this->Model->create():在 $this->Model->save() 之前调用它是完全可以的,甚至推荐。这就像变量初始化 - 当您绝对确定自己在做什么时,您可以跳过它,但需要您自担风险。

要解决 Missing argument 1 for ProyectosController::anadir() 错误,您应该在此处发布您的 URL。它应该类似于 /proyectos/anadir/2/10

So it still looks (as deizel suggested) that you've got id set in your $this->data somehow, probably a field with mistaken in a form, not sure (you can post your view here so we can take a look). The best way to check it is to monitor actual SQL queries; put this after $this->Model->save() (without adding $this->Model->create()yet, for debug purposes):

$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);

Add output of above to your question.

Regarding $this->Model->create(): calling it prior to $this->Model->save() is perfectly ok and even recommended. It's like variable initialization - you can skip it, but at your own risk, when you're absolutely sure what you're doing.

To address Missing argument 1 for ProyectosController::anadir() error you should post your URL here. It should be something like /proyectos/anadir/2/10.

万水千山粽是情ミ 2024-11-30 21:47:50

如果此时数据中存在 ID,CakePHP 将执行更新:

            if ($this->Proyecto->save($this->data)) { ...

取消注释以下行并检查是否没有 $this->data['Proyecto']['id'] 值:

//                        print_r($this->data);

CakePHP will perform an update if an ID exists in your data at this point:

            if ($this->Proyecto->save($this->data)) { ...

Uncomment the following line and check there is no $this->data['Proyecto']['id'] value:

//                        print_r($this->data);
趴在窗边数星星i 2024-11-30 21:47:50

通过@lxa的评论,我让它以这种方式运行:

用这个替换function anadir(我也删除了评论):

function anadir($cliente_id, $nombre) {
    if (!empty($this->data)) {
                $this->Proyecto->create();
        if ($this->Proyecto->save($this->data)) {
            $this->Session->setFlash('El proyecto ha sido grabado.');
            $this->redirect(array('controller'=>'clientes', 'action'=>'listar'));
        }
        } else {  
            $this->data['Proyecto']['cliente_id'] = $cliente_id; 
        }
        $this->set('idcliente', $cliente_id);
        $this->set('nombrecliente', $nombre);
}

这行确实可以解决问题:

$this- >Proyecto->create();

它运行了,但我不知道它是否真的正确。

我终于开始看到 Symfony2 了。也许学习曲线会比cakephp更大,但是cakephp给了我很多外键和数据库处理方式的问题。

问候并感谢有人试图回答。

With the comment of @lxa I have get it to run in this way:

Replace function anadir with this one (I have remove comments too):

function anadir($cliente_id, $nombre) {
    if (!empty($this->data)) {
                $this->Proyecto->create();
        if ($this->Proyecto->save($this->data)) {
            $this->Session->setFlash('El proyecto ha sido grabado.');
            $this->redirect(array('controller'=>'clientes', 'action'=>'listar'));
        }
        } else {  
            $this->data['Proyecto']['cliente_id'] = $cliente_id; 
        }
        $this->set('idcliente', $cliente_id);
        $this->set('nombrecliente', $nombre);
}

Really this line does the trick:

$this->Proyecto->create();

It runs but I don't know if it is really right or not.

At last I am starting to see Symfony2. Perhaps the learning curve will be bigger than cakephp, but cakephp is given me a lot of problems with foreign keys and the way of do on databases.

Greetings and thanks to somebody trying to answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文