Help with a simple Join

Asked

Viewed 59 times

2

Good evening, I don’t know what I’m doing wrong, I have two models, in Migration I created like this

Schema::create('endereco_tipos', function (Blueprint $table) {
         $table->increments('id');
         $table->string('nome');
         $table->timestamps();
         $table->softDeletes();
     });


Schema::create('endereco', function (Blueprint $table) {
        $table->increments('id');            
        $table->string('estado', 2)->default('PR');    
        $table->string('cidade', 300);   
        $table->string('bairro', 300);     
        $table->string('logradouro', 300);
        $table->string('logradouro_numero', 15);
        $table->string('residencia_numero', 15)->nullable();
        $table->string('complemento1', 300)->nullable();
        $table->string('complemento2', 300)->nullable();
        $table->string('responsavel', 300)->nullable();
        $table->integer('endereco_tipo_id')->unsigned();
        $table->foreign('endereco_tipo_id')->references('id')->on('endereco_tipos');
        $table->timestamps();
        $table->softDeletes();
    });

In the classes I left so

namespace teste;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

use Eloquent;

class Endereco extends Eloquent
{
    use SoftDeletes;
    protected $table = 'endereco';  
    protected $dates = ['deleted_at', 'created_at', 'updated_at'];
    public function enderecoTipo(){
        return $this.hasOne(EnderecoTipo::class, 'endereco_tipo_id');
    }
}

namespace teste;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

use Eloquent;

class EnderecoTipo extends Eloquent
{
    use SoftDeletes;
    protected $table = 'endereco_tipos';
    protected $dates = ['deleted_at', 'created_at', 'updated_at'];
    public function endereco(){
        return $this->belongsTo(Endereco::class);
    }
}

Inside my controller if I call it so it works no more returns the type

$todos = Endereco::all();
return view("enderecos.index", ['todos' => $todos]);

I don’t know how to load the type address next to the address, I tried to do so

$todos = Endereco::with('enderecoTipo')->get();

but I had such a comeback -> Call to undefined function teste\hasOne()

I tried to do so but it load the object with the address data mixed with the address type data

$todos = Endereco::join("endereco_tipos", "endereco.endereco_tipo_id", "=", "endereco_tipos.id")->get();

I wish you would return me a json like this

{ 
    id:15, 
    estado:'asdasda', 
    cidade:'asdada', 
    enderecoTipo : { id: 7, nome: 'Casa', .... } ,
    .....
}

In the view I put like this {{ $todos }}, then gave a print_r and it is noticed that for some reason there is no reference to the EnderecoTipo::class within the Endereco::class

  • Your relationship is not configured in the model for not being a key within the convention it does not make relationships even have answer already on the site

  • Possible duplicate of Save Relationship 1:1 on Laravel 5.3

  • I looked at the link you passed and did not find the solution, for me ta giving the error Call to Undefined Function hasOne test()

  • What would be a key within the convention?

  • I changed there in the code of Return $this->belongsTo(Address::class); to Return $this->hasMany(Address::class); but the error continues, please help me, the link you passed me did not answer anything, my relationship is 1:N and not 1:1 I had spelled wrong, but keeps appearing Call to Undefined Function hasOne test()

  • If the relationship is 1:N I have also answered: How to use hasmany relationship in Laravel 5.2?, your model is pulling the namespace wrong and it’s not heritage with Eloquent it’s with Model, Observer all this!

Show 1 more comment

1 answer

1

Your models are all off the charts, they’re on namespaces different from the standard and when it happens, it needs to be registered and configured so that the recognize them, honestly I think unnecessary, for reasons of loss of pattern, there is no gain and do so, etc, if there’s no reason to do it so what to do?, another thing is that the use are wrong, the spelling and settings too, ie many mistakes, because when you say function teste\hasOne not defined, already have the problem where the inheritance is made wrong, are many mistakes and I will put a minimal example through both Migrations made available of an ideal model:

Addressypes (table: address_types)

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Enderecotipos extends Model
{
    use SoftDeletes;

    protected $fillable = array('nome');
    protected $table = 'endereco_tipos';
    public $timestamps = true;
    protected $primaryKey = 'id'; 
    protected $dates = ['deleted_at'];  

    public function enderecos()
    {
        return $this->hasMany(Endereco::class,'endereco_tipo_id','id');
    }    
}

Address (table: address)

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Endereco extends Model
{
    use SoftDeletes;

    protected $fillable = array('estado', 'cidade', 'bairro',
        'logradouro', 'logradouro_numero', 'residencia_numero',
        'complemento1', 'complemento2','responsavel', 'endereco_tipo_id');
    protected $table = 'endereco';
    public $timestamps = true;
    protected $primaryKey = 'id';

    protected $dates = ['deleted_at'];  

    public function enderecotipo()
    {
        return $this->belongsTo(Enderecotipos::class,'endereco_tipo_id','id');
    }    
}

Remarks: observe and compare the two models well with your models and check everything you need to use in yours to make it work, remember that I put in namespace pattern of for the Model and I go beyond, create a paste inside app by the name of Models and I organize my application like this, but I did it in a standard way for studies and that serve as guidance to others as well and there is already an answer to your doubt: How to use hasmany relationship in Laravel 5.2? which can also be used with reference.

References

  • Just putting your classes in my classes said that class Enderecotipos not found, kept the namespace Test, you said I did wrong but I at first rode php Artisan app:name Test, so when I circled php Artisan make:model Address He already created with the Test namespace, when I generated the controller and the routes I generated by Artisan. and it generates with this Test namespace. I will create a new application to test with the standard namespace of Alavel, Guenta ai

  • Bizarre with the default namespace works, another question just, I’m making the query so $all = Addresswith::with("addresstype")->get(); and it works, but when I delete an Addresstype it keeps bringing the addresses of that type, it comes so { id : 7, addressype : null }, {id : 8, addressype : { id : 15 }} understand? i would like the item that the type address is null not show, has as?

  • @Thiagoschmitz actually you did not delete the address physically in the bank, because it exists there since you are using softdelete, and it happens naturally, it is so, now you can filter the addresses that have value or not that is another doubt, perhaps opening a new question would be ideal, and this has already solved the problem of your question, clarified better?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.