php - 如何从 Laravel 5.5 中的一对多关系中删除单行(多行)

标签 php laravel eloquent one-to-many relation

我在 Laravel 中有两个模型:Label

class Label extends \Eloquent
{
    protected $fillable = [
        'channel_id',
        'name',
        'color',
    ];

    public function channel()
    {
        return $this->belongsTo('App\Channel');
    }
}

和 channel

class Channel extends \Eloquent
{
    protected $fillable = [
        'name',
    ];

    public function labels()
    {
        return $this->hasMany('App\Label');
    }

}

现在当标签被删除时,我想确定标签属于 channel 。

这非常有效,因为它甚至是原子的,所以如果标签确实属于该 channel ,则该行将被删除。

标签 Controller :

/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $channel = $this->getChannel();

    Label::where('id', $id)
        ->where('channel_id', $channel->id)
        ->delete();

    return back();
}

现在我的问题是:如何使用 Eloquent 构建它,使其优雅?像这样的东西:

    $channel->labels()->destroy($id);

但是关系上没有销毁函数。

更新:

我设法在正确的方向上取得了一些成就:

$channel->labels()->find($id)->delete();

这将删除带有 $id 的标签,但前提是该标签分配了正确的 channel_id。如果没有,我会收到以下错误,我可以捕获并处理该错误:

FatalThrowableError (E_ERROR) Call to a member function delete() on null

不过,由于 Apache 是线程化的,因此可能会出现另一个线程在我读取后更改 channel_id 的情况。所以除了我的查询之外,唯一的方法是运行事务?

最佳答案

如果你想删除模型的相关项而不是模型本身,你可以这样做:

$channel->labels()->delete(); 它将删除与 channel 相关的所有标签。

如果你只想删除一些标签,你可以使用 where()

$channel->labels()->where('id',1)->delete();

此外,如果您的关系是多对多关系,它也会从第三个表中删除。

关于php - 如何从 Laravel 5.5 中的一对多关系中删除单行(多行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47718096/

相关文章:

php - 使用keyby集合方法检索eloquent api资源

php - 如何将数据从 jQuery 传递到 php 以保存到数据库中?

php - 为什么图像路径没有保存在数据库中?

php - vtiger crm : single csv file to multiple database table

php - "&reg"被转换为 "®"

php - Laravel 显示数据库中的图像

php - Laravel 子查询

php - Laravel NotFoundHttpException 虽然路由存在

php - 如何仅在 LIKE 查询 Laravel 中找到整个单词?

php - Laravel 自定义模型方法