OctoberCMS 获取正在保存的组件的 ID

OctoberCMS get id of component being saved

我正在尝试使用上传文件的路径更新 table,以便通过电子邮件发送下载文件 link,但我似乎无法获取 ID。

我的组件如下所示:

public function onAddJob() {
    $manual = new Job();
    $manual->company = Input::get('company_name');
    $manual->ordered_by = Input::get('client_name');
    $manual->ordered_by_email = Input::get('client_email');
    $manual->emergency_no = Input::get('emergency_no');
    $manual->instructions = Input::get('instructions');
    $manual->project_name = Input::get('project_name');
    $manual->fileupload = Input::file('fileuploader');
    $manual->save();
    $this->id = $this->property('id');
    Db::table('manual_jobs')->where('id', $this->id)->update(['path' => $manual->fileupload->getPath()]);

一切都很好,但路径没有更新,因为我没有正确获取 id,谁能帮我看看我在哪里?

这是因为当你调用ajax request时它不会调用pageCycle.

作为 result,您的 code in pagenot executed

您页面上的代码可能如下所示

{% component 'yourComponent' id=someID %}

但此代码在 ajax call

期间是 not executed

to execute page code during ajax call you need to explicitly call $this->controller->pageCycle()

所以新代码看起来像

public function onAddJob() {

    // we are calling page code explicitly 
    $this->controller->pageCycle();

    $manual = new Job();
    $manual->company = Input::get('company_name');
    $manual->ordered_by = Input::get('client_name');
    ... other code
}

也参考这个答案

Link :

如果您仍然发现问题,请发表评论。

解决方案比我想象的要简单得多。 我要找的是这个:

$manual->id

因此更新查询如下所示:

Db::table('manual_jobs')->where('id', $manual->id)->update(['path' => $manual->fileupload->getPath()]);

id组件由模型上的变量$primaryKey定义

默认主键是'id'对应数据库table字段名为id

您可以通过将 $primaryKey 设置为另一个键来覆盖默认键名

class Foo extends Model {
     $primaryKey = 'foo_id';
}

为什么我要解释这个是因为你不需要知道字段的名称。

您可以做的是:

$foo = new Foo();
$foo->bar = 'baz';
$foo->save();

echo $foo->getKey();
echo $foo->getAttribute($foo->getKeyName());
echo $foo->{$foo->primaryKey}

他们都会打印出对象上新创建的主键。

getkey() returns 主键的值。
getKeyName() returns 模型中定义的主键字段名称