Home > Article > Backend Development > Association between models in different databases in Laravel, laravel model association_PHP tutorial
Assume that the relationship between ModelA and ModelB is BelongsTo
If they both belong to the same database connection
Then
<span>public</span> <span>function</span><span> a(){ </span><span>return</span> <span>$this</span>->belongsTo("ModelA"<span>) }</span>
If the two models belong to different databases
Then
<span>public</span> <span>function</span><span> a() { </span><span>$instance</span> = <span>new</span><span> ModelA; </span><span>$instance</span>->setConnection(<span>$a_conn</span><span>); </span><span>$query</span> = <span>$instance</span>-><span>newQuery(); </span><span>return</span> <span>new</span> BelongsTo(<span>$query</span>, <span>$this</span><span>); }</span>