Laravel中如何从对象变量中提取指定列的ID值?
The core issue here is that your getLatestTag method uses ->get(), which returns a Collection of objects (even if there's only one matching tag). When you store this collection in $productTagIds, each element is a collection, not a single ID value. Here's how to fix this:
1. Modify the getLatestTag Method to Return the ID Directly
Update your TagModel method to fetch just the tag ID instead of the entire collection. Use value('id') to get the single integer ID (or null if no matching tag exists):
public static function getLatestTag($name) { return DB::table('tags') ->where('is_deleted', 0) ->where('name', $name) ->value('id'); // Returns the ID as an integer, or null }
2. Adjust the Controller Logic to Store IDs
Now when you call this method, it will return the ID directly. Your controller loop can be simplified to store the IDs in $productTagIds:
$productTagIds = []; foreach ($newTags as $newTag) { $tagId = TagModel::getLatestTag($newTag); // Optional: Skip if tag doesn't exist to avoid null values if ($tagId) { $productTagIds[] = $tagId; } } $productId = (int)ProductManagementModel::getMaxId(); foreach ($productTagIds as $productTagId) { $productTag = new ProductTagModel; $productTag->product_id = $productId; $productTag->tag_id = $productTagId; // Now this is an integer ID $productTag->save(); }
Alternative: Return a Single Tag Instance
If you need the entire tag object for other purposes later, use ->first() instead of ->get() to get a single stdClass object (or null):
public static function getLatestTag($name) { return DB::table('tags') ->where('is_deleted', 0) ->where('name', $name) ->first(); }
Then in your controller, access the id property explicitly:
foreach ($newTags as $newTag) { $tag = TagModel::getLatestTag($newTag); if ($tag) { $productTagIds[] = $tag->id; } }
Key Notes
- Always handle cases where the tag might not exist (check for
nullbefore using the value) to avoid "Trying to get property 'id' of non-object" errors. - The
dd($id)line in your original controller code is likely a typo (since$idisn't defined there) – you can remove or adjust it as needed.
内容的提问来源于stack exchange,提问作者Binod Paneru

