php - Laravel 5.2 - 使用带有数组值的附加方法
问题描述
我正在用 Laravel 5.2 中的帖子创建一个博客。每个帖子都会有多个标签。我创建了帖子和标签之间的关系。创建帖子后,我正在尝试为其附加多个标签。
控制器功能
public function store(Request $request)
{
$attributes = [
'author_id' => Auth::user()->id,
'title' => $request->input('title'),
'text' => $request->input('text'),
];
$post = Post::create($attributes);
// Get the tag ids from the the tags table in the database
$tagsList = $request->input('tags');
$tags = explode(",", $tagsList);
$tagIds = array();
foreach($tags as $tag) {
$tagIds[] = Tag::select('id')->where('name', $tag)->limit('5')->get();
}
dd($tagIds); // Output below
$post->tags()->attach($tagIds); // not working
}
dd($tagIds) 输出
array:2 [▼
0 => Collection {#316 ▼
#items: array:1 [▼
0 => Tag {#317 ▼
#fillable: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:1 [▼
"id" => 32
]
#original: array:1 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
1 => Collection {#318 ▼
#items: array:1 [▼
0 => Tag {#319 ▼
#fillable: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:1 [▼
"id" => 36
]
#original: array:1 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
]
返回的数组包含正确的标签 ID。我只是不知道如何将它们转换为格式,以便可以将它们传递给附加方法。
我会非常感谢任何形式的帮助!
解决方案
为方便起见,附加和分离也接受 ID 数组作为输入:
$tagIds = array();
foreach($tags as $tag) {
$tagIds[] = Tag::select('id')->where('name', $tag)->first()->id;
}
dd($tagIds); // Output below
/*
Array
(
[0] => 1
[1] => 3
[2] => 5
)
*/
$post->tags()->attach($tagIds);
推荐阅读
- forms - 有没有办法让 Firefox 与 macOS 钥匙串一起工作?如果不是很好的替代密码管理器?
- javascript - 如何将打字稿类型的字符串转换为字符串数组?
- python - 从 URL、RE、python 中提取 Amzon ASIN
- youtube-api - Youtube API 一频道二 ID
- laravel - PhpWord TemplateProcessor 克隆表行并在其中插入信息
- r - Plotly:如何在圆环图中自定义颜色?
- azure - 当刷新令牌和用户帐户详细信息未缓存在令牌缓存中时,是否有任何方法可以使用 MSAL.net 静默获取令牌
- python - 如何从我的数据中获取填充的等高线图?
- sql - 如何使用 oracle 表函数将 json 转换为列和行
- python - 在 python 3.7 中使用黑色作为预提交钩子