ActiveRecord::primaryKeySingle()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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