yadakhov
7/23/2015 - 8:54 PM

Laravel MyModel class

Laravel MyModel class

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model as Eloquent;

/**
 * This class acts as our Base Model
 *
 * @package App\Models
 */
class Model extends Eloquent
{
    /**
     * Return the table name from a static function
     *
     * @return string
     */
    public static function getTableName()
    {
        $class = get_called_class();

        return (new $class)->getTable();
    }

    /**
     * Return the primary key name from a static function
     *
     * @return string
     */
    public static function getPrimaryKey()
    {
        $class = get_called_class();

        return (new $class)->getKeyName();
    }

    /**
     * Where In Hashed by primary key
     *
     * @param array $ids
     * @return array
     */
    public static function whereInHash(array $ids, $column = 'primaryKey')
    {
        $modelName = get_called_class();

        $primaryKey = static::getPrimaryKey();

        if ($column === 'primaryKey') {
            $column = $primaryKey;
        }

        $rows = $modelName::whereIn($column, $ids)->get();

        $out = [];

        foreach ($rows as $row) {
            $out[$row->$primaryKey] = $row;
        }

        return $out;
    }

    /**
     * Create a hash amp of two columns
     *
     * @param $keyColumn
     * @param $valueColumn
     * @param array $ids
     * @return array
     */
    public static function createMap($keyColumn, $valueColumn, array $ids, $column = 'primaryKey')
    {
        $modelName = get_called_class();

        $primaryKey = static::getPrimaryKey();

        if ($column === 'primaryKey') {
            $column = $primaryKey;
        }

        $rows = $modelName::select([$keyColumn, $valueColumn])->whereIn($column, $ids)->get();

        $out = [];

        foreach ($rows as $row) {
            $out[$row->$keyColumn] = $row->$valueColumn;
        }

        return $out;
    }
}