Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
nescafe Avatar asked Jan 05 '23 12:01

nescafe


2 Answers

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()
like image 125
Captain Fail Avatar answered Jan 11 '23 06:01

Captain Fail


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();
like image 28
Robin De Schepper Avatar answered Jan 11 '23 07:01

Robin De Schepper