分享方式:


什麼是建置者?

您可以使用建立器來新增實體。 每個父物件,例如 Campaign,都包含取得您用來新增子實體之產生器物件的方法。 例如,若要將廣告群組新增至行銷活動,您會呼叫 Campaign 物件的 newAdGroupBuilder 方法。

Builder 物件包含用來設定實體屬性值的方法。 例如,若要指定關鍵字的[檢視],您會使用 withCpc 方法。 設定實體的所有屬性值之後,您會呼叫 build 方法來建立實體。 建置程式是非同步程式,要求會與其他建置要求一起排入佇列,並在批次中處理。 批次處理的要求會在腳本終止之前完成。

若要判斷建置要求是否成功,您可以查看記錄,或使用方法傳回的 build 工作物件。 例如, AdGroupBuilder 會傳回 AdGroupOperation。 您可以 (、 getResultgetErrors) isSuccessful 呼叫工作物件的任何方法,以判斷腳本是否成功建立實體。 但在呼叫這些方法時,有一些效能考慮 (請參閱效能 考慮) 。

下列範例在概念上示範如何使用產生器和工作物件建立關鍵字。 您應該只在建立單一實體 (或幾個) 時,才使用此流程。

    // Gets the first ad group in the account.
    var adGroup = AdsApp.adGroups().get().next();

    // Use the 'with' methods to specify the keyword's property values.
    // The .build() method adds the build request to the build queue.
    var keywordOperation = adGroup.newKeywordBuilder()
        .withCpc(1.2)
        .withText("shirts")
        .withFinalUrl("https://www.contoso.com/shirts")
        .build();

    // Call isSuccessful() to determine if the build succeeded.
    // Calling any of the operation object's method processes the
    // build request immediately. 
    if (keywordOperation.isSuccessful()) {
        // You only need to call getResult if you need to access
        // the new keyword entity.
        var keyword = keywordOperation.getResult();
    } else {
        // Handle the errors.
        for (var error of keywordOperation.getErrors()) {
            Logger.log(`${error}\n`);
        }
    }

效能考量

為了改善效能,腳本會批次處理建置要求。 如果您呼叫建置要求的作業方法,它會強制腳本立即處理已排入佇列的組建要求,以降低任何效能提升。 如果您要建立多個實體,請勿在用來建置實體的相同迴圈中執行作業方法。 這會導致效能不佳,因為一次只會處理一個實體。 相反地,請建立作業的陣列,並在建置迴圈之後加以處理。

執行此動作

    // An array to hold the operations, so you 
    // can process them after all the entities are queued.
    var operations = []; 

    // Create all the new entities.
    for (var i = 0; i < keywords.length; i++) {
        var keywordOperation = AdsApp.adGroups().get().next()
          .newKeywordBuilder()
          .withText(keywords[i])
          .build();
        operations.push(keywordOperation);
    }

    // Now call the operation method so the build requests
    // get processed in batches.
    for (var i = 0; i < operations.length; i++) {
        var newKeyword = operations[i].getResult();
    }

別這樣

    for (var i = 0; i < keywords.length; i++) {
        var keywordOperation = AdsApp.adGroups().get().next()
          .newKeywordBuilder()
          .withText(keywords[i])
          .build();

        // Don't get results in the same loop that creates
        // the entity because Scripts then only processes one
        // entity at a time.
        var newKeyword = keywordOperation.getResult();
    }

以下是產生器清單。

後續步驟