nescafe
nescafe

Reputation: 187

Getting table name using Eloquent Relationship

class SampleELoq extends Model
{
    use SoftDeletes;

    public function conditionFields() {
       return $this->belongsToMany('App\EloquentModel\ConditionField');
    }
}

nameSpace is the name space of the SampleELoq

$Eloq = $nameSpace::find(1);

$table = with(new $nameSpace->conditionFields)->getTable();

print_r(Schema::getColumnListing($table));

How can i able to get the table name of the conditionFields?

Upvotes: 6

Views: 6575

Answers (4)

Robin De Schepper
Robin De Schepper

Reputation: 6365

You don't have to retrieve a model from the database like in Catain Fail's answer: you can obtain the related table name in any situation as follows:

$relation = (new MyModel)->myRelationship(); // Returns a Relations subclass like BelongsTo or HasOne.
$relatedModel = $relation->getRelated(); // Returns a new empty Model
$tableName = $relatedModel->getTable();

Or in short:

$tableName = (new MyModel)->myRelationship()->getRelated()->getTable();

Upvotes: 6

Captain Fail
Captain Fail

Reputation: 77

To get table from conditionFields you need return relation model, then you can get table by getTable method. Some like this

Model::first()->conditionFields()->getRelated()->getTable()

Upvotes: 5

Rutvij Kothari
Rutvij Kothari

Reputation: 1285

After digging hard I found a solution. It can be achieved like this.

$tableName = (new SampleELoq)->conditionFields()->getTable();

In General

$tableName = (new MODELCLASS)->RELATIONSHIP()->getTable();

Upvotes: 1

Ahmed farag mostafa
Ahmed farag mostafa

Reputation: 2944

you have two ways :-

     dd(Model::$table);

or inside your model :-

 dd($this->table());

Upvotes: 0

Related Questions