【问题标题】:Why attach method returns null in Laravel?为什么附加方法在 Laravel 中返​​回 null?
【发布时间】:2016-10-13 10:35:39
【问题描述】:

我有 3 个表 posts、tags 和一个数据透视表 post_tag。

post_tag 表是:

+----+-------------+--------+
| id |   post_id   | tag_id |
+----+-------------+--------+
|  1 |           1 |      2 |
|  2 |           2 |      2 |
|  3 |           3 |      1 |
|  4 |           4 |      1 |
|  5 |           4 |      3 |
|  6 |           5 |      3 |
+----+-------------+--------+

我在Post 模型中有这个:

class Post extends Model {  
    public function tags() {
        return $this->belongsToMany('Tag'); 
    }
}

这在Tag 模型中:

class Tag extends Model {       
    public function posts() {
        return $this->belongsToMany('Post');
    }
}

现在在我的控制器中,我试图将记录插入数据透视表post_tag:

$post = Post::find(4);
$post_tag = $post->tags()->attach(2);
return $post_tag //it returns null

所以,我需要在数据透视表中获取已创建记录的详细信息,但 $post_tag 包含 null!

如何获取数据透视表上最后插入记录的详细信息(如 id ,...)?

【问题讨论】:

    标签: php mysql laravel eloquent laravel-5.2


    【解决方案1】:

    您可能需要检查sync() 方法,该方法还返回一个附加的 id 数组:

    $post = Post::find(4);
    $post_tag = $post->tags()->sync([2], false);
    var_dump($post_tag['attached']);
    

    输出:

    array(1) {
        [0]=>
        int(2)
    }
    

    请注意,false 参数应作为第二个参数传递,以避免分离所有其他行。

    【讨论】:

      【解决方案2】:

      attach 方法不返回任何东西,这就是你得到 null 的原因。要检查记录是否插入成功,您需要再次调用 DB。它类似于删除方法。请查看this 以获取附加方法的参考。

      【讨论】:

      • 是的,你是对的。但我认为attach 方法没有返回任何东西太糟糕了!
      猜你喜欢
      • 2012-06-13
      • 2015-10-10
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多