【问题标题】:Laravel 5.1 firstOrNew with relationshipsLaravel 5.1 firstOrNew 与关系
【发布时间】:2015-11-28 00:12:59
【问题描述】:

如何在 Laravel 关系中使用 firstOrNew 方法。

我有以下关系:

/**
 * The rows that belong to the timesheet.
 *
 * @return Object
 */
public function rowTimesheet()
{
    return $this->hasMany('App\Models\Timesheet\RowTimesheet');
}

我正在尝试使用以下内容为数据库中的时间表创建一个新行。我没有收到任何错误,但没有插入该行。

有什么想法吗?

/**
 * Create timesheet rows.
 *
 * @param $id
 * @param $row
 */
public function createTimesheetRow($id, $row) 
{
    return $this->timesheet->find($id)->rowTimesheet()->firstOrNew($row);
}

【问题讨论】:

  • ->firstOrNew($row) 之后尝试了->save()

标签: php laravel laravel-5


【解决方案1】:

你好firstOrNew

firstOrNew 返回的模型尚未持久化到数据库中。你需要手动调用 save 来持久化它

你可以试试

public function createTimesheetRow($id, $row) 
{
    return $this->timesheet->find($id)->rowTimesheet()->firstOrCreate($row);
}

public function createTimesheetRow($id, $row) 
{
    $row = $this->timesheet->find($id)->rowTimesheet()->firstOrNew($row);
    return $row->save();
}

您可以在Laravel Docs阅读更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 2017-04-16
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    相关资源
    最近更新 更多