Passed
Push — master ( d5d166...eae9c0 )
by Tõnis
02:28
created

ActiveRecord::primaryKeySingle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace andmemasin\myabstract;
4
5
use yii\db\ActiveRecord as BaseActiveRecord;
6
use yii\base\NotSupportedException;
7
8
/**
9
 * Class ActiveRecord
10
 * @package andmemasin\myabstract
11
 * @author Tõnis Ormisson <[email protected]>
12
 */
13
class ActiveRecord extends BaseActiveRecord
14
{
15
    /**
16
     * Get the primary key column as string if the one-column PK
17
     * NB! Always use single column Primary-keys!
18
     * NB! this assumes that primary key always has the table_name_id format
19
     * @return string
20
     * @throws NotSupportedException if multi-column PrimaryKey is used
21
     */
22
    public function primaryKeySingle()
23
    {
24
        if (count(static::primaryKey()) === 1) {
25
            return static::primaryKey()[0];
26
        }
27
        throw new NotSupportedException('Not supported for multi-column primary keys');
28
    }
29
30
    /** {@inheritdoc} */
31
    public function hasMany($class, $link = null)
32
    {
33
        if (empty($link)) {
34
            $link = [$this->primaryKeySingle() => $this->primaryKeySingle()];
35
        }
36
        return parent::hasMany($class, $link);
37
    }
38
39
    /** {@inheritdoc} */
40
    public function hasOne($class, $link = null)
41
    {
42
        if (empty($link)) {
43
            $link = [$this->primaryKeySingle() => $this->primaryKeySingle()];
44
        }
45
        return parent::hasOne($class, $link);
46
    }
47
48
}