You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何从对象变量中提取指定列的ID值?

Solution to Extract Tag ID from Object in Laravel

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 null before 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 $id isn't defined there) – you can remove or adjust it as needed.

内容的提问来源于stack exchange,提问作者Binod Paneru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:53:43