doujiao4710 2016-06-13 05:36
浏览 76

为什么attach方法在Laravel中返回null?

I have 3 tables posts,tags, and a pivot table post_tag.

post_tag table is :

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

I have this in Post model :

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

And this in Tag model :

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

Now in my Controller I'm trying to insert a record to the pivot table post_tag :

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

So, I need to get details of created record in pivot table, but $post_tag contains null!

How can I get the details(like id ,...) of last inserted record on the pivot table?

  • 写回答

2条回答 默认 最新

  • duanfanta6741 2016-06-13 05:55
    关注

    The attach method doesn't return any thing, this is why you are getting null. To check if record was inserted successfully you would need to make another call to DB. It is similar to Delete method. Check this for reference to attach method.

    评论

报告相同问题?

悬赏问题

  • ¥15 BV260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序