简体   繁体   English

在Laravel 5.3中处理雄辩的关系

[英]Dealing with Eloquent relationships in Laravel 5.3

I have the following tables created using Schema s: 我使用Schema创建了以下表:

  Schema::create('typen', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
  });

 Schema::create('auktionen', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('typ')->unsigned();

    $table->foreign('typ')->references('id')->on('typen');
  });

The table typen is only created once at contains fixed values: typen仅在包含固定值的情况下创建一次:

Typen
id| name
1 | Typ 1
2 | Typ 2
...

Those values are constant, no more will be added during the application lifetime. 这些值是恒定的,在应用程序生命周期内不会再添加任何值。 So every Auktion I create should be associated with one Typ . 因此,我创建的每个Auktion都应与一个Typ相关联。 I created the model for Auktion and thought of it as a one-to-one relationship (is this correct?). 我为Auktion创建了模型, Auktion其视为一对一的关系(对吗?)。

I would like to create an Auktion with a given Typ using Eloquent queries like this: 我想使用这样的口才查询来创建具有给定类型的Auktion:

  $thetyp = App\Typ::where("id", "=", 1)->first();
  $auktion->typ()->associate($thetyp);

and fetch the name of the Typ of my Auktion : 并取name中的Typ我的Auktion

$auktion->typ->name;

Currently my model looks like this for Auktion : 目前,我的模型在Auktion看起来像这样:

  public function typ()
  {
    return $this->hasOne('App\Typ', 'typ');
  }

which is not working. 这是行不通的。 I already tried setting different relationships but I just end in different error codes ranging from undefined methods (associate() to an error where an SQL statement failed trying to update my typen table (when using save() - which I really do not want to). 我已经尝试设置不同的关系,但是我遇到的错误代码范围很广,从未定义的方法(associate()到一个错误,在该错误中,SQL语句尝试更新我的typen表失败(使用save() ,我真的不想这样做) )。

Can someone clarify this problem for me and explain which relationship I have to use? 有人可以为我澄清这个问题并解释我必须使用哪种关系吗?

EDIT1 : As mentioned in a comment I already tried using belongsTo in Auktion model EDIT1 :如评论中所述,我已经尝试在Auktion模型中使用belongsTo

  public function typ()
  {
    return $this->belongsTo('App\Typ', 'typ');
  }

which results in Undefined property: App\\Auktion::$typ when calling 导致Undefined property: App\\Auktion::$typ调用时Undefined property: App\\Auktion::$typ

 $thetyp = App\Typ::where("id", "=", 1)->first();
 $auktion->typ()->save($thetyp);

and when calling $auktion->typ->name; 并在调用$auktion->typ->name; in

Trying to get property of non-object

EDIT2 : 编辑2

I just figured that 我只是觉得

echo $auktion->typ()->first()->name;

is indeed working. 确实在工作。 But referring to this answer this should be the same as 但是参考这个答案应该与

echo $auktion->typ->name;

What exactly am i doing wrong? 我到底在做什么错?

EDIT3 : 编辑3

I tried using suggested code: 我尝试使用建议的代码:

  $thetyp = App\Typ::find($typ);
  $auktion->typ->save($thetyp);

After I navigated to the view ehere I run the code I got this: 在导航到该视图之后,我运行了代码:

在此处输入图片说明

I got this the second time today, somwhow out of nowhere 我今天第二次拿到这个

Your second edit makes a lot of sense. 您的第二次编辑很有意义。 Your method name is typ but that's also the name of the column. 您的方法名称是typ但这也是列的名称。 So when you use $auktion->typ() it's actually loading the relationship. 因此,当您使用$auktion->typ()它实际上是在加载关系。 When you use $auktion->typ it's grabbing the value of that column. 当您使用$auktion->typ它将获取该列的值。

You need to either continue working this way using the parenthesis to load the relation and no parenthesis to grab the value of the column, or you can change the name of the column to something better such as typ_id which is ultimately what Laravel expects it to be and should save you from more similar headaches down the road. 您需要继续使用圆括号来加载关系,而不需要使用圆括号来获取列的值,或者将列的名称更改为更好的名称(例如typ_id ,这最终是Laravel期望的)并可以避免以后遇到更多类似的麻烦。

Here is some code enhancement: 这是一些代码增强功能:

 $thetyp = App\Typ::where("id", "=", 1)->first();
 $auktion->typ()->save($thetyp);

To: 至:

//Will return null if Model is not found
$thetyp = App\Typ::find(1);
//You actually have to retrieve the relationship, because calling typ()
//will only retrieve the Relationship query
$auktion->typ()->get()->save($thetyp);

The problem is that the relationship is defined backwards. 问题在于关系是向后定义的。 You need to make Auction belongTo Type, and change Type to hasMany Auctions. 您需要将Auction设置为belongTo类型,并将Type更改为hasMany Auctions。 The statement would read: 该语句将显示为:

"A Type has many Auctions. An Auction has one Type". “一种类型有很多拍卖。一种拍卖有一种类型”。

Here are the classes (in English, sorry, my German is bad :( so I just did it in English) with the migrations: 这是与迁移有关的课程(英语,对不起,我的德语不好:(所以我只是用英语做了):

-Auction class: -拍卖类:

class Auction extends Model
{
    protected $table = 'auction';

    public function type()
    {
        return $this->belongsTo('App\Type');
    }
}

-Auction migration: -拍卖迁移:

Schema::create('auction', function(Blueprint $table){

$table->increments('id');
$table->integer('type_id')->references('id')->on('type')->nullable();
$table->string('title')->nullable();
$table->string('description')->nullable();

$table->timestamps();

});

-Type class: -类型类:

class Type extends Model
{
    protected $table = 'type';

    public function auction()
    {
        return $this->hasMany('App\Auction');
    }
}

-Type migration: -类型迁移:

 Schema::create('type', function(Blueprint $table){

      $table->increments('id');
      $table->string('name');

      $table->timestamps();
 });

First, you can create a Type object (or insert it with a query) so we can have a Type row that we can relate to an Auction object/entry, and do the following: 首先,您可以创建一个Type对象(或在查询中插入它),以便我们可以拥有一个与Auction对象/条目相关的Type行,并执行以下操作:

//Example of Type obj creation

$type = new Type();
$type->name = 'Type #1';
//Don't forget to save
$type->save();

//OR find/retrieve a Type obj

//Where $id is the id of the Type obj, else the obj will be null
$type = Type::find($id);

$auction = new Auction();

$auction->title = 'Title #1';
$auction->description = 'Test description';

$auction->type_id = $type->id;

//Don't forget to save
$auction->save();

Now later in your code, whenever you are using an Auction object and you want to retrieve the associated type (if any), you can use: 现在,在代码的稍后部分,每当您使用Auction对象并且想要检索关联的类型(如果有)时,都可以使用:

$type = $auction->type()->get();

Which will return the instance of Type , and you will be able to retrieve the property name like so: 这将返回Type的实例,您将能够像下面这样检索属性名称:

$type->name

I hope this helps! 我希望这有帮助! Let me know if you have any more questions! 让我知道您是否还有其他问题!

You can try this in your Auktion model 您可以在Auktion模型中尝试

$thetyp = App\Typ::find(1);
$auktion->typ->save($thetyp);

Now fetch 现在获取

$auktion->typ->name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM