Elgg\Database\RelationshipsTable::add PHP Method

add() public method

This function lets you make the statement "$guid_one is a $relationship of $guid_two". In the statement, $guid_one is the subject of the relationship, $guid_two is the target, and $relationship is the type.
public add ( integer $guid_one, string $relationship, integer $guid_two, boolean $return_id = false ) : boolean | integer
$guid_one integer GUID of the subject entity of the relationship
$relationship string Type of the relationship
$guid_two integer GUID of the target entity of the relationship
$return_id boolean Return the ID instead of bool?
return boolean | integer
    public function add($guid_one, $relationship, $guid_two, $return_id = false)
    {
        if (strlen($relationship) > \ElggRelationship::RELATIONSHIP_LIMIT) {
            $msg = "relationship name cannot be longer than " . \ElggRelationship::RELATIONSHIP_LIMIT;
            throw new \InvalidArgumentException($msg);
        }
        // Check for duplicates
        // note: escape $relationship after this call, we don't want to double-escape
        if ($this->check($guid_one, $relationship, $guid_two)) {
            return false;
        }
        $sql = "\n\t\t\tINSERT INTO {$this->db->prefix}entity_relationships\n\t\t\t       (guid_one, relationship, guid_two, time_created)\n\t\t\tVALUES (:guid1, :relationship, :guid2, :time)\n\t\t\t\tON DUPLICATE KEY UPDATE time_created = :time\n\t\t";
        $params = [':guid1' => (int) $guid_one, ':guid2' => (int) $guid_two, ':relationship' => $relationship, ':time' => $this->getCurrentTime()->getTimestamp()];
        $id = $this->db->insertData($sql, $params);
        if (!$id) {
            return false;
        }
        $obj = $this->get($id);
        $result = $this->events->trigger('create', 'relationship', $obj);
        if (!$result) {
            $this->delete($id, false);
            return false;
        }
        return $return_id ? $obj->id : true;
    }

Usage Example

Example #1
0
 /**
  * {@inheritdoc}
  */
 public function add($guid_one, $relationship, $guid_two, $return_id = false)
 {
     $rel = $this->check($guid_one, $relationship, $guid_two);
     if ($rel) {
         return false;
     }
     $this->iterator++;
     $id = $this->iterator;
     $row = (object) ['id' => $id, 'guid_one' => (int) $guid_one, 'guid_two' => (int) $guid_two, 'relationship' => $relationship, 'time_created' => $this->getCurrentTime()->getTimestamp()];
     $this->rows[$id] = $row;
     $this->addQuerySpecs($row);
     return parent::add($row->guid_one, $row->relationship, $row->guid_two, $return_id);
 }