/** * Insert a belongsToMany foreign key relationship. * * @param string recordName * @param Relation $relation * @param int $columnValue * @return void */ protected function insertBelongsToMany($recordName, Relation $relation, $columnValue) { $joinTable = $relation->getTable(); $this->tables[] = $joinTable; $relatedRecords = explode(',', str_replace(', ', ',', $columnValue)); foreach ($relatedRecords as $relatedRecord) { list($fields, $values) = $this->buildBelongsToManyRecord($recordName, $relation, $relatedRecord); $placeholders = rtrim(str_repeat('?, ', count($values)), ', '); $sql = "INSERT INTO {$joinTable} ({$fields}) VALUES ({$placeholders})"; $sth = $this->db->prepare($sql); $sth->execute($values); } }
/** * Join pivot or 'through' table. * * @param \Illuminate\Database\Eloquent\Model $parent * @param \Illuminate\Database\Eloquent\Relations\Relation $relation * @param string $type * @return void */ protected function joinIntermediate(Model $parent, Relation $relation, $type) { if ($relation instanceof BelongsToMany) { $table = $relation->getTable(); $fk = $relation->getForeignKey(); } else { $table = $relation->getParent()->getTable(); $fk = $table . '.' . $parent->getForeignKey(); } $pk = $parent->getQualifiedKeyName(); if (!$this->alreadyJoined($join = (new Join($type, $table))->on($fk, '=', $pk))) { $this->query->joins[] = $join; } }