Trying to get matching id's
from a table and inserting them again in the same table under differnet relationship.
$contentPack = ContentPack::find($id);
$cloned_pack_goals = DB::table('content_pack_goal')->where('content_pack_id' , $contentPack->id)->get();
$cloned_pack_goal_ids = $cloned_pack_goals->goal_id;
Produces Exception
Exception
Property [goal_id] does not exist on this collection instance.
dd($cloned_pack_goals);
outputs:
Illuminate\Support\Collection {#2466 ▼
#items: array:2 [▼
0 => {#3129 ▼
"goal_id": 4
"content_pack_id": 2
}
1 => {#2467 ▼
"goal_id": 9
"content_pack_id": 2
}
]
}
How to get goal_ids
from the output to insert them into the same table again but with a different relation?
$newPack = $contentPack->replicate();
DB::table('content_pack_goal')->insert(['content_pack_id' => $newPack->id,'goal_id' => $cloned_pack_goal_ids]);
Am doing something wrong when getting the ID's and when inserting them. tried using ->first();
it works but only one id
gets inserted
CodePudding user response:
To get an array of only the Ids, use pluck()
and toArray()
$cloned_pack_goal_ids = DB::table('content_pack_goal')
->where('content_pack_id' , $contentPack->id)
->pluck('goal_id') // returns a collection of only Ids.
->toArray(); // returns an array from the collection.
CodePudding user response:
Write your query in this format this will give you the require output:
$cloned_pack_goals = DB::table('content_pack_goal')->where('content_pack_id' , $contentPack->id)->get()->toArray(); $cloned_pack_goal_ids = $cloned_pack_goals[0]->goal_id;
CodePudding user response:
$cloned_pack_goals is a collection, so you need to exclude goal_ids from all collection records separately. This snippet may help you:
$cloned_pack_goals->pluck('goal_ids')->toArray();
it gives you an array containing all goal ids.