Ask Your Question
1

Is it possible to determine if a table column is a foreign key using Laravel's Model?

asked 2023-04-28 17:58:21 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-04-28 18:24:02 +0000

woof gravatar image

Yes, it is possible to determine if a table column is a foreign key using Laravel's Model. You can use the getConnection method to get the connection instance from the model and then use the getDoctrineSchemaManager method to get the schema manager instance. Finally, you can use the listTableForeignKeys method of the schema manager to get a list of foreign keys for the table, and check if the column in question is one of them. Here is an example code snippet:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class YourModel extends Model
{
    public function isForeignKey($column)
    {
        $connection = $this->getConnection();
        $schemaManager = $connection->getDoctrineSchemaManager();
        $table = $this->getTable();
        $foreignKeys = $schemaManager->listTableForeignKeys($table);

        foreach ($foreignKeys as $foreignKey) {
            $localColumns = $foreignKey->getLocalColumns();
            if (in_array($column, $localColumns)) {
                return true;
            }
        }

        return false;
    }
}

You can then call the isForeignKey method on an instance of your model and pass in the column name as a parameter to check if it is a foreign key. For example:

$model = new YourModel;
$isForeignKey = $model->isForeignKey('some_column');
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-28 17:58:21 +0000

Seen: 18 times

Last updated: Apr 28 '23