Home > Article > Backend Development > Association between models in different databases in Laravel
Suppose 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>
The above introduces the relationship between the models of different databases in Laravel, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.