-1

There is a Client Model and a Lead model:

class Client extends Model
{
    protected $fillable = [
        'fn',
        'ln'
    ];

    public function fullName()
    {
        return new Attribute(
            get: fn () => $this->fn . ' ' . $this->ln;
        );
    }
}
class Lead extends Model
{
    protected $fillable = [
        'full_name'
    ];

    public function client()
    {
        return $this->hasOne(Client::class, 'full_name', 'full_name');
    }
}

As you can see, I try to build a relationship from the Lead to the Client model, so that I can use Lead::first()->client. But my try looks for clients.full_name what is not existing in the database.

How can I implement this relationship?

In tinker I proved, that there is a match:

> Lead::first()->full_name === Client::first()->full_name
= true
JanBoehmer
  • 395
  • 3
  • 14
  • 1
    you can't use a "accessor" in queries .. one is on the PHP side after the fact and the other is at the database level ... it doens't exist in the database – lagbox Mar 05 '23 at 19:13
  • Yes, that's what I already know/see, what brings me to ask a question here – JanBoehmer Mar 05 '23 at 19:14
  • You can try this : `return $this->hasOne(Client::class, 'fn')->whereRaw('CONCAT(fn, " ", ln) = ?', [$this->full_name]);` – Vins Mar 05 '23 at 19:27
  • I would say it's not working. I translated it to work with SQLite what I am using `return $this->hasOne(Client::class, 'fn')->whereRaw('fn || " " || ln = ?', [$this->full_name]);` but `Lead::first()->client` returns null. As you can see from my tinker example, the first Lead has a matching client. You provide a key of fn, but there is no clients.fn = leads.full_name – JanBoehmer Mar 05 '23 at 19:48

1 Answers1

-1

You can use custom sql query


use Illuminate\Support\Facades\DB;

class ...Controller extends Controller
{
    public function ...(){
        $leads = DB::select("SELECT `leads`.* 
        FROM `clients` 
        INNER JOIN `leads` ON `leads`.`full_name` = CONCAT(`clients`.`fn`,' ',`clients`.`ln`);");

        // code ...
    }
}
Masunulla
  • 55
  • 3